ImagePaint is a shape style that fills a shape by repeating a region of an image. We can use this shape style to tile images as strokes or fills.
We will use following image for this example.
Since ImagePaint conforms to ShapeStyle protocol, we can use it as a fill color.
struct DevTechieImagePaintExample: View {
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20)
.fill(ImagePaint(image: Image("flower")))
.frame(width: 200, height: 200)
Text("DevTechie")
.font(.largeTitle)
}
}
}
We can set strokeStyle with ImagePaint as well.
struct DevTechieImagePaintExample: View {
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20)
.stroke(ImagePaint(image: Image("flower")), lineWidth: 40)
.frame(width: 300, height: 200)
Text("DevTechie")
.font(.largeTitle)
}
}
}
ImagePaint takes scale as a parameter, we can use this parameter to scale the image to match our app’s need. Scale factor is applied to the image while its being drawn.
struct DevTechieImagePaintExample: View {
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20)
.stroke(ImagePaint(image: Image("flower"), scale: 1.5), lineWidth: 40)
.frame(width: 300, height: 200)
Text("DevTechie")
.font(.largeTitle)
}
}
}
ImagePaint has another parameter called sourceRect which is a unit-space rectangle defining how much of the source image to draw and where to draw the image from.
struct DevTechieImagePaintExample: View {
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20)
.stroke(ImagePaint(image: Image("flower"), sourceRect: CGRect(x: 0.2, y: 0.2, width: 0.5, height: 0.5), scale: 1.0), lineWidth: 40)
.frame(width: 300, height: 200)
Text("DevTechie")
.font(.largeTitle)
}
}
}
With that we have reached the end of this article. Thank you once again for reading. Don’t forget to subscribe our newsletter at https://www.devtechie.com