gpt4 book ai didi

ios - 在 drawRect 中绘制透明的 UIBezierPath 线

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:58:04 26 4
gpt4 key购买 nike

我试图在 drawRect 方法中实现透明路径。这是我创建的简单代码:

override func drawRect(rect: CGRect) {
let clippingPath = UIBezierPath()

UIColor.whiteColor().set();
clippingPath.moveToPoint(CGPoint(x: 10, y: CGRectGetHeight(self.bounds) / 2))
clippingPath.addLineToPoint(CGPoint(x: CGRectGetWidth(self.bounds) - 10, y: CGRectGetHeight(self.bounds) / 2))
clippingPath.lineWidth = 6
clippingPath.lineCapStyle = .Round
clippingPath.stroke()
}

这是结果:

enter image description here

有没有办法尝试保持背景纯色但路径线透明。如果我将第二行更改为 UIColor.clearColor().set() 似乎什么也没有发生,我只是得到一个完整的纯色背景(在本例中为黑色。

最佳答案

您想使用 kCGBlendModeDestinationOut 的混合模式(和纯色描边)绘制路径。

According to the docs ,此混合模式执行以下操作:

R = D*(1 - Sa)

哪里...

  • R为预乘结果。

  • S 是源颜色,包括 alpha

  • D 是目标颜色,包括 alpha

  • Ra、Sa 和 Da 是 R、S 和 D 的 alpha 分量

这样,当与纯笔触颜色一起使用时,绘制的路径将是“透明的”。

clearColor 对您不起作用的原因是因为默认混合模式是加法,因此生成的颜色不会受到绘制带有 alpha 的颜色的影响0 在它上面。另一方面,DestinationOut减法

因此您需要执行以下操作:

override func drawRect(rect: CGRect) {

let clippingPath = UIBezierPath()

let context = UIGraphicsGetCurrentContext() // get your current context

// draw your background color
UIColor.greenColor().set();
CGContextFillRect(context, bounds)

CGContextSaveGState(context) // save the current state

CGContextSetBlendMode(context, .DestinationOut) // change blend mode to DestinationOut (R = D * (1-Sa))

// do 'transparent' drawing

UIColor.whiteColor().set();
clippingPath.moveToPoint(CGPoint(x: 10, y: CGRectGetHeight(self.bounds) / 2))
clippingPath.addLineToPoint(CGPoint(x: CGRectGetWidth(self.bounds) - 10, y: CGRectGetHeight(self.bounds) / 2))
clippingPath.lineWidth = 6
clippingPath.lineCapStyle = .Round
clippingPath.stroke()

CGContextRestoreGState(context) // restore state of context

// do further drawing if needed
}

注意:

您必须将 View 的 opaque 属性设置为 false 才能工作,否则 UIKit 将假定它具有不透明的内容。例如:

override init(frame: CGRect) {
super.init(frame: frame)
opaque = false
}

关于ios - 在 drawRect 中绘制透明的 UIBezierPath 线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35724906/

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