【发布时间】:2017-01-23 07:51:56
【问题描述】:
我正在使用非常方便的 UIColor(patternImage:) 在带有 Xcode 8.2 的 iOS 10 应用程序中创建一些带有平铺图案的 CAShapeLayers。平铺总是从视图的原点开始,如果您希望它从其他地方开始,这可能会很不方便。为了说明,下面是模拟器的截图(代码如下):
左边的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 调整图案的相位,以便两个图块都显示完整的脸。 Apple 为 UIColor(patternImage:) 提供的 documentation 有用地指代了用于此目的的函数:
要更改相位,请将颜色设为当前颜色,然后使用 setPatternPhase(_:) 改变相位的函数。
听起来很简单!但我很难实现它。我不太确定“使颜色成为当前颜色”是什么意思。我尝试获取当前上下文并在其上调用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 的建议下,在调用 setPatternPhase 之前,我使用 UIImage 的 .set() 为当前上下文设置当前笔画和填充。不幸的是,输出不受影响。这是我尝试过的代码:
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 的模式的相位转换?
【问题讨论】:
标签: ios swift calayer uicolor cashapelayer