I have a masked image that's utilized by a UIBezierPath()
and I'd like to have a border around the masked portion rather than the original image. I've come this close in my (countless number) attempt through trial and error and, tirelessly, given up. Any easier way to do this?
This is how far I've come to my goal:
I'd love to have the border go inward! :-(
Swift 2 Code:
let picture = UIImageView(image: UIImage(named: "myPicture.png"))
picture.layer.contentMode = .ScaleAspectFit
picture.layer.clipsToBounds = true
let maskLayer = CAShapeLayer()
picture.layer.mask = maskLayer
maskLayer.frame = CGRect(origin: CGPointZero, size: picture.image.size)
let radius = picture.size.width/2
let center = CGPoint(x: picture.size.width/2, y: picture.size.height/2)
let path = UIBezierPath()
path.moveToPoint(center)
path.addArcWithCenter(center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI*2.0*0.2), clockwise: true)
maskLayer.path = path.CGPath
picture.layer.mask = maskLayer
picture.layer.borderWidth = 3
picture.layer.borderColor = UIColor.purpleColor().CGColor
picture.layer.cornerRadius = picture.layer.bounds.width/2
答案 0 :(得分:1)
假设我理解你的意思是“我喜欢让边框向内” - 我建议使用另一个CAShapeLayer
将边框显示为描边路径,并将其作为子图层添加到你的图像视图的图层。
您只需在为面具定义的路径中设置传递,设置strokeColor
和lineWidth
,并将fillColor
设置为clearColor
。
这样的事情可以解决问题:
// insert your image here
guard let img = UIImage(named: "4.png") else {
return
}
// frame of your image view
let frame = CGRectInset(view.bounds, 10, 10)
// your picture view
let pictureView = UIImageView(image: img)
pictureView.frame = frame
pictureView.contentMode = .ScaleAspectFit
pictureView.clipsToBounds = true
// the radius and center of your path
let radius = pictureView.frame.size.width*0.5
let center = CGPoint(x: pictureView.frame.size.width*0.5, y: pictureView.frame.size.height*0.5)
// your masking & stroking path
let path = UIBezierPath()
path.moveToPoint(center)
path.addArcWithCenter(center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI*2.0*0.8), clockwise: true)
path.closePath()
// the layer used to mask the image view
let maskLayer = CAShapeLayer()
maskLayer.frame = pictureView.bounds
maskLayer.path = path.CGPath
pictureView.layer.mask = maskLayer
// the layer used to draw the border
let strokeLayer = CAShapeLayer()
strokeLayer.frame = pictureView.bounds
strokeLayer.fillColor = UIColor.clearColor().CGColor
strokeLayer.path = path.CGPath
strokeLayer.strokeColor = UIColor.purpleColor().CGColor
strokeLayer.lineWidth = 10
pictureView.layer.addSublayer(strokeLayer)
view.addSubview(pictureView)
提供以下输出:
另外,我会注意到你在OP中提供的代码甚至没有编译 - 请始终从IDE复制并粘贴代码,而不是自己输入代码!