Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a see-through Rectangle in SwiftUI

Tags:

swiftui

I want to make an Image 100% transparent through a small rectangle and 50% transparent from all others. As if making a small hole to see-through the small rectangle. Here is my code...

struct ImageScope: View {

    var body: some View {
        ZStack {
            Image("test_pic")

            Rectangle()
                .foregroundColor(Color.black.opacity(0.5))

            Rectangle()
                .frame(width: 200, height: 150)
                .foregroundColor(Color.orange.opacity(0.0))
                .overlay(RoundedRectangle(cornerRadius: 3).stroke(Color.white, lineWidth: 3))
        }
    }
}

For easier understanding...

enter image description here

like image 471
Asim Roy Avatar asked Apr 21 '20 13:04

Asim Roy


1 Answers

Here is working approach. It is used custom shape and even-odd fill style.

Tested with Xcode 11.4 / iOS 13.4

Below demo with more transparency contrast for better visibility.

demo

struct Window: Shape {
    let size: CGSize
    func path(in rect: CGRect) -> Path {
        var path = Rectangle().path(in: rect)

        let origin = CGPoint(x: rect.midX - size.width / 2, y: rect.midY - size.height / 2)
        path.addRect(CGRect(origin: origin, size: size))
        return path
    }
}

struct ImageScope: View {

    var body: some View {
        ZStack {
            Image("test_pic")

            Rectangle()
                .foregroundColor(Color.black.opacity(0.5))
                .mask(Window(size: CGSize(width: 200, height: 150)).fill(style: FillStyle(eoFill: true)))

            RoundedRectangle(cornerRadius: 3).stroke(Color.white, lineWidth: 3)
                .frame(width: 200, height: 150)
        }
    }
}

backup

like image 60
Asperi Avatar answered Sep 22 '22 10:09

Asperi