将图像添加到CALayer / CAShapeLayer始终显示黑色

时间:2016-08-17 18:41:34

标签: ios swift

我试图在圆形CAShapeLayer中添加图片,所以我开始创建一个这样的圆圈:

let circleContainer = UIBezierPath(arcCenter: pCenter, radius: radius - 10, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true)
let imageSubLayer = CAShapeLayer()
imageSubLayer.path = circleContainer.CGPath

self.view.layer.addSublayer(imageSubLayer)

然后添加我做的图像:

let imageLayer = CALayer()
imageLayer.contents = UIImage(named: "pic")?.CGImage
imageSubLayer.addSublayer(imageLayer)

//I've also tried adding the image directly to the circular CAShapeLayer like so but without any success:
imageSubLayer.contents = UIImage(named: "pic")?.CGImage

问题是:当我运行应用程序时,circleContainer始终显示黑色(请参见下图)。我究竟做错了什么 ? 提前谢谢!

enter image description here

1 个答案:

答案 0 :(得分:1)

您没有设置imageLayer的框架。但目前还不清楚你究竟想要实现什么。如果您希望图像遮罩到形状图层,则需要将其设置为imageLayer的遮罩属性:

let imageLayer = CALayer()
imageLayer.contents = UIImage(named: "pic")?.CGImage
imageLayer.frame = view.bounds
imageLayer.mask = imageSubLayer
view.layer.addSublayer(imageLayer)

更新

如果您在drawRect中有此代码,则可以直接绘制到视图的CGContext。例如:

override func drawRect(rect: CGRect)
{
    super.drawRect(rect)
    let circleRect = CGRectInset(self.bounds, 10, 10)
    let path = UIBezierPath(ovalInRect: circleRect)
    path.lineWidth = 10
    UIColor.yellowColor().set()
    path.stroke()
    path.fill()
    path.addClip()
    let image = UIImage(named: "pic")
    image?.drawInRect(circleRect)
}

上面的代码绘制了一个黄色圆圈,中心的图像被剪切到圆圈的边界。