Sitemap

How to create dashed border in NativeScript

2 min readDec 18, 2024

--

One of the things you may probably need to add to an application is a dash line. The first thing that comes to mind is to set it with:

border-style: dashed;

But it doesn’t work that way in NativeScript. Here you can see the list of supported properties of the NativeScript View class works https://docs.nativescript.org/api/class/View.

Not being able to style borders is not an issue of NativeScript, but of native iOS/Android platforms.

Good solution might be to use Canvas. To do this, we will use the Canvas plugin from the NativeScript community @nativescript-community/ui-canvas.

We will not dwell on the installation process, everything is described in the documentation @nativescript-community/ui-canvas#installation.

Get Igor Bezlepkin’s stories in your inbox

Join Medium for free to get updates from this writer.

We will make an example of code implementation in NativeScript with Vue. This can be done in the same way with Angular, react, Svelte, or plain JS/TS as well.

<GridLayout rows="*">
<Image
width="16"
height="16"
src="res://plus_icon"
stretch="aspectFit"
horizontalAlignment="center"
verticalAlignment="center"
/>

<CanvasView width="80" height="80" @draw="onDraw"></CanvasView>
</GridLayout>

As you can see, the code is as simple as possible. Using CanvasView component we will create our border and using Image component we will add a “plus” icon.
You can learn how to work with images and resources from the official documentation at https://docs.nativescript.org/ui/image.

Our main goal is to make a dotted border.

<script lang="ts" setup>
import { Canvas, createRect, DashPathEffect, Direction, Paint, Path, Style } from '@nativescript-community/ui-canvas';
import { Color } from '@nativescript/core';

const onDraw = (event: { canvas: Canvas }): void => {
const canvas = event.canvas;
const path = new Path();
const paint = new Paint();
const rect = createRect(0, 0, 80, 80);

path.addRoundRect(rect.left, rect.top, rect.right, rect.bottom, 10, 10, Direction.CW);
paint.setStyle(Style.STROKE);
paint.strokeWidth = 1;
paint.setColor(new Color('#65adf1'));
paint.setPathEffect(new DashPathEffect([2, 2], 2));

canvas.drawPath(path, paint);
}
</script>

This code creates a square 80 wide and 80 high with rounded corners with a radius of 10. Using the DashPathEffect class we set the thickness, length and distance of the dashed line.

Here’s what we got as a result on Android and on iOS.

Press enter or click to view image in full size

If you enjoyed this post…it would mean a lot to me if you could click on the “claps” icon…up to 50 claps allowed — Thank You!

--

--

Igor Bezlepkin
Igor Bezlepkin

Written by Igor Bezlepkin

Software Developer | I develop primarily web/cross-platform applications using technologies such as NodeJs, NestJs, Fastify, NativeScript, Angular