ios 如何在SwiftUI中获取掩码量或百分比?

3hvapo4f  于 11个月前  发布在  iOS
关注(0)|答案(1)|浏览(71)

当应用蒙版修改器时,是否可以获得可见蒙版的数量或百分比?我试图使用Canvas实现一个刮刮卡视图,我想在80%可见后完全显示黄色 * 内容 * 视图。


的数据
以下是我目前掌握的信息:

struct ScratchCardView: View {
    @State var points = [CGPoint]()
    
    var body: some View {
        ZStack {
            // MARK: Scratchable overlay view
            RoundedRectangle(cornerRadius: 20)
                .fill(.red)
                .frame(width: 250, height: 250)

            // MARK: Hidden content view
            RoundedRectangle(cornerRadius: 20)
                .fill(.yellow)
                .frame(width: 250, height: 250)
                .mask(
                    Path { path in
                        path.addLines(points)
                    }.stroke(style: StrokeStyle(lineWidth: 50, lineCap: .round, lineJoin: .round))
                )
                .gesture(
                    DragGesture(minimumDistance: 0, coordinateSpace: .local)
                        .onChanged({ value in
                            points.append(value.location)
                        })
                        .onEnded({ _ in
                           // TODO: detect content view visibility
                        })
                )
        }
    }
}

字符串
任何帮助都是感激不尽的。

a14dhokn

a14dhokn1#

得到笔画部分的面积是相当困难的。我会通过在正方形内采样一些点来近似这个,看看有多少点在笔画部分内。从我做的几个测试来看,我觉得这已经足够好了,特别是因为你有这么大的笔画宽度。
首先获取表示描边区域的CGPath

let cgpath = Path { path in
    path.addLines(points)
}.cgPath
// remember to use the same parameters here as you did in the StrokeStyle!
let contourPath = cgpath.copy(strokingWithWidth: 50, lineCap: .round, lineJoin: .round, miterLimit: 10)

字符串
然后,在正方形中找到一些点进行采样。在这里,我将大正方形分成5*5个小正方形,并选择每个小正方形中心的点。

var count = 0
for i in 0..<5 {
    for j in 0..<5 {
        let point = CGPoint(x: 25 + i * 50, y: 25 + j * 50)
        if contourPath.contains(point) {
            count += 1
        }
    }
}
if count > 20 {
    print("More than 75%!")
}

相关问题