gpt4 book ai didi

ios - UIView.mask 设置颜色

转载 作者:搜寻专家 更新时间:2023-11-01 06:16:28 26 4
gpt4 key购买 nike

我有一个 50 像素的正方形 UIView,我将其设置为我的 super View 的掩码。

let squareView = UIView(frame...)

self.view.mask = squareView

结果是一个 50px 的正方形透明区域,但它周围的 mask 区域的颜色始终是白色。如何将透明方 block 周围的 mask 区域的颜色更改为黑色?

 _______________
| |
| <-------------- Masked area that I would like to change the color of
| |
| 000000 |
| 000000 <-------- squareView: becomes transparent as expected
| 000000 |
| 000000 |
| |
| |
| |
|_______________|

最佳答案

我认为这是演示您想要的效果的代码片段。您应该能够将它作为 Xcode 模板创建的 View Controller 的 viewDidLoad() 方法粘贴到新的“单一 View ”iOS 项目中。

我需要一些方法来设置 mask View 的内容而不创建 UIView 的子类(因为我很懒)所以我的示例创建了一个图像(其 alpha channel 最多为 1.0部分带有 100x100 平方的透明 Alpha channel )。我将其设置为 mask View 的内容。

最后的计时器只是循环显示外部 View 的一堆颜色,因为......这很有趣。

override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blue

let overallView = UIView(frame: CGRect(x:100, y:100, width:300, height:300))
overallView.backgroundColor = UIColor.green

// Draw a graphics with a mostly solid alpha channel
// and a square of "clear" alpha in there.
UIGraphicsBeginImageContext(overallView.bounds.size)
let cgContext = UIGraphicsGetCurrentContext()
cgContext?.setFillColor(UIColor.white.cgColor)
cgContext?.fill(overallView.bounds)
cgContext?.clear(CGRect(x:100, y:100, width: 100, height: 100))
let maskImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

// Set the content of the mask view so that it uses our
// alpha channel image
let maskView = UIView(frame: overallView.bounds)
maskView.layer.contents = maskImage?.cgImage
overallView.mask = maskView

self.view.addSubview(overallView)

var hue = CGFloat(0)
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) {
(_) in
let color = UIColor(hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
hue = hue + (1.0/20);
if hue >= 1.0 { hue = 0 }

overallView.backgroundColor = color
}
}

关于ios - UIView.mask 设置颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788913/

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