gpt4 book ai didi

ios - 自定义 View 绘图 - View 内的孔

转载 作者:行者123 更新时间:2023-11-28 12:13:03 25 4
gpt4 key购买 nike

View是怎么画成这样的。

经过研究我得到了可以使用context.fillRects方法。但是如何为此找到确切的矩形。

let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.red.cgColor)
context?.setAlpha(0.5)
context?.fill([<#T##rects: [CGRect]##[CGRect]#>])

如何实现这个结果?

enter image description here

背景:蓝色。

Overlay(紫色):50% 不透明度,中间有方孔

最佳答案

首先创建您的 View ,然后使用两个 UIBezierPaths 绘制所有内容:一个描述内部矩形(孔),另一个沿着屏幕边界运行(externalPath)。这种绘制方式确保中间的蓝色矩形是一个真正的洞,而不是绘制在紫色 View 之上。

let holeWidth: CGFloat = 200

let hollowedView = UIView(frame: view.frame)
hollowedView.backgroundColor = UIColor.clear

//Initialise the layer
let hollowedLayer = CAShapeLayer()

//Draw your two paths and append one to the other
let holePath = UIBezierPath(rect: CGRect(origin: CGPoint(x: (view.frame.width - holeWidth) / 2, y: (view.frame.height - holeWidth) / 2), size: CGSize(width: holeWidth, height: holeWidth)))
let externalPath = UIBezierPath(rect: hollowedView.frame).reversing()
holePath.append(externalPath)
holePath.usesEvenOddFillRule = true

//Assign your path to the path property of your layer
hollowedLayer.path = holePath.cgPath
hollowedLayer.fillColor = UIColor.purple.cgColor
hollowedLayer.opacity = 0.5


//Add your hollowedLayer to the layer of your hollowedView
hollowedView.layer.addSublayer(hollowedLayer)

view.addSubview(hollowedView)

结果是这样的: enter image description here

关于ios - 自定义 View 绘图 - View 内的孔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47810573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com