如何在 SwiftUI 中创建透明矩形 [英] How to create a see-through Rectangle in SwiftUI

查看:32
本文介绍了如何在 SwiftUI 中创建透明矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一个小矩形使图像 100% 透明,并使所有其他图像 50% 透明.好像打了一个小孔来透视这个小矩形.这是我的代码...

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))
        }
    }
}

为了更容易理解...

推荐答案

这是工作方法.使用自定义形状和奇偶填充样式.

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

使用 Xcode 11.4/iOS 13.4 测试

Tested with Xcode 11.4 / iOS 13.4

下面的演示具有更高的透明度对比度以获得更好的可见性.

Below demo with more transparency contrast for better visibility.

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)
        }
    }
}

这篇关于如何在 SwiftUI 中创建透明矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆