Reputation: 656
After searching numerous sources on how to mask an image in Swift, I've found many that utilize UIImage rather than UIImageView. It's getting quite confusing because they are almost similar yet they don't share some of the same subclasses & properties.
I have an image that will be added into a stacks view although I'd like this image to be masked with a circular shape with a fixed start and end angle.
Example:
Original Picture and Desired Mask Result
I'd like to emphasize that I am simulating a pie being sliced out so essentially I am cropping an image with the Pie's size.
Here's what I've attempted so far to get started (and I keep failing)...
let testPicture:UIImageView = UIImageView(image: UIImage(named: "myPicture"))
testPicture.contentMode = .ScaleAspectFit
testPicture.layer.borderWidth = 1
testPicture.clipsToBounds = true
testPicture.layer.masksToBounds = true
view.layer.addSublayer(shapeLayer)
// ???
// UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise).CGPath
self.myStackView.addArrangedSubview(testPicture)
self.myStackView.layoutIfNeeded()
I just can't figure out how to apply the same implementation of masking images with geometric functions when other sources out there solely use UIImage.
New Code (Attempt) to Generate Pie Mask
let center = CGPointMake(testPicture.frame.size.width / 2, testPicture.frame.size.height / 2)
let radius = CGFloat((CGFloat(testPicture.frame.size.width) - CGFloat(1.0)) / 2)
let midX = (testPicture.layer.frame.width-testPicture.layer.frame.width)/2
let midY = (testPicture.layer.frame.height-testPicture.layer.frame.height)/2
let circlePath = UIBezierPath(arcCenter: CGPoint(x: midX , y: midY), radius: radius, startAngle: CGFloat(10), endAngle:CGFloat(M_PI * 2), clockwise: true)
let maskLayer = CAShapeLayer()
maskLayer.path = circlePath.CGPath
testPicture.layer.mask = maskLayer
testPicture.clipsToBounds = true
testPicture.layer.masksToBounds = true
Upvotes: 0
Views: 996
Reputation: 41236
To mask a layer you assign a separate layer to the mask
property. In this case, I think what you're looking for is:
testPicture.layer.mask = shapeLayer
Upvotes: 2