gpt4 book ai didi

ios - 如何在 Swift 中更改 UIColor patternImage 的相位?

转载 作者:行者123 更新时间:2023-11-28 08:18:53 25 4
gpt4 key购买 nike

我正在使用非常方便的UIColor(patternImage:)创造一些CAShapeLayer在带有 Xcode 8.2 的 iOS 10 应用程序中使用平铺模式。平铺总是从 View 的原点开始,如果您希望它从其他地方开始,这可能会很不方便。为了说明这一点,下面是模拟器的屏幕截图(下面的代码):

Tiling problem

CAShapeLayer左边从 (0,0) 开始,所以一切都很好。右边的那个在 (110,50),所以它在中间分开。这是代码:

let firstBox = CAShapeLayer()
firstBox.fillColor = UIColor(patternImage: UIImage(named: "test-image")!).cgColor
view.layer.addSublayer(firstBox)
firstBox.path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 100, height: 100)).cgPath

let secondBox = CAShapeLayer()
secondBox.fillColor = UIColor(patternImage: UIImage(named: "test-image")!).cgColor
view.layer.addSublayer(secondBox)
secondBox.path = UIBezierPath(rect: CGRect(x: 110, y: 50, width: 100, height: 100)).cgPath

我想调整右图的相位CAShapeLayer这样两 block 瓷砖都显示出完整的脸。苹果的documentation for UIColor(patternImage:) 有助于引用用于此目的的函数:

To change the phase, make the color the current color and then use the setPatternPhase(_:) function to change the phase.

听起来很简单!但我很难实现它。我不太确定“使颜色成为当前颜色”是什么意思。我尝试获取当前上下文并调用 setPatternPhase在其上,在为图层分配填充颜色之前和之后:

UIGraphicsGetCurrentContext()?.setPatternPhase(CGSize(width: 25, height: 25))

无明显影响。我尝试将包含 UIView 的子类化并在其 drawRect: 中设置相位方法,如 this answer 中所建议.但是drawRect:在 Swift 中不存在,所以我都尝试了 draw(_ rect:)draw(_ layer:, in:) .两个函数都被调用,但没有明显的效果。

class PatternView: UIView {
override func draw(_ rect: CGRect) {
UIGraphicsGetCurrentContext()?.setPatternPhase(CGSize(width: 25, height: 25))
super.draw(rect)
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
ctx.setPatternPhase(CGSize(width: 25, height: 25))
super.draw(layer, in: ctx)
}
}

在 Dave Weston 的建议下,我使用了 UIImage.set()在调用 setPatternPhase 之前为当前上下文设置当前笔划和填充.不幸的是,输出不受影响。这是我试过的代码:

let secondBoxColor = UIColor(patternImage: UIImage(named: "test-image")!)
secondBoxColor.set()
UIGraphicsGetCurrentContext()?.setPatternPhase(CGSize(width: 50, height: 50))

let secondBox = CAShapeLayer()
secondBox.fillColor = secondBoxColor.cgColor
view.layer.addSublayer(secondBox)
secondBox.path = UIBezierPath(rect: CGRect(x: 110, y: 50, width: 100, height: 100)).cgPath

我怎样才能将绘制到 CAShapeLayer 中的图案相移? ?

最佳答案

要使您的图案成为当前颜色,您应该在包含您的图案的UIColor 实例上调用set() 实例方法。这会将颜色配置为当前上下文的当前描边和填充颜色。

然后,根据 Apple 的文档,setPatternPhase 应该起作用。

关于ios - 如何在 Swift 中更改 UIColor patternImage 的相位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41801464/

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