I'm trying to add an image inside a circular CAShapeLayer
so i started by creating a circle like so :
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)
then to add the image i did:
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
the problem is: the circleContainer
is always showing black color when i run the app (see image below). what am i doing wrong ? thanks in advance!
You've not set the frame of imageLayer
. But it's also not clear what exactly you're trying to achieve. If you want your image to mask to your shape layer you'll need to set it to the mask property of imageLayer
:
let imageLayer = CALayer()
imageLayer.contents = UIImage(named: "pic")?.CGImage
imageLayer.frame = view.bounds
imageLayer.mask = imageSubLayer
view.layer.addSublayer(imageLayer)
If you have this code in drawRect
you can draw directly into the CGContext
of the view. For example:
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)
}
The above code draws a yellow circle with an image in the center clipped to the bounds of the circle.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.