Axy
Axy

Reputation: 384

Apply a dashed border to a masked Image in SwiftUI

I have an Image that is masked by an image asset. I'd like to apply a dashed border to the Image so that the dashed border shape follows the mask whatever it is.

Image(uiImage: self.helper.loadedImage!)
.resizable()
.scaledToFill()
.foregroundColor(Color.clear)
.background(Color.clear)
.frame(width: 200, height: 200, alignment: .center)
.clipped()
.mask(Image(uiImage: self.helper.loadedMaskImage!)
.resizable()
.frame(width: 200, height: 200, alignment: .center))

This image is rendered correctly. If loadedMaskImage is a circle for example, i see the original image in a circle shape. Now i'd like to show a circle dashed border on this image. But I don't want to use any specific shape, because the loadedMaskImage can be anything at runtime. Is this possible without diving back into UIKit UIView?

EDIT: This is how i can mask the view. In this case i'm using a circle image as a mask and the result is correct. Now on top of this i'd like to have a dashed border that has the same shape of that circle.

enter image description here

Upvotes: 1

Views: 1589

Answers (1)

Tilak Madichetti
Tilak Madichetti

Reputation: 4346

The dashed border can be achieved by using a dashed stroke of color over the image using a ZStack

 Circle()
    .stroke(Color.blue, style: StrokeStyle(lineWidth:5 , lineCap: .round, dash:[10, 5]))
    .frame(width: 200, height: 200)


The dash argument is an array where here it means for every 10 length of showing the border there should be 5 length of no border which appears as dashed border,

I set the width and height of the frame exactly equal to your image's width and height so that it looks as though the circle is just bordering your image

You can set the first property to anything like Color.black.opacity(0.4) or even a LinearGradient if you wish so...

Upvotes: 1

Related Questions