LoginSignup
6
6

More than 5 years have passed since last update.

角丸(cornerRadius)のUIImageViewにボーダー(border)をつけるExtension

Posted at

やりたいこと

角丸にしたUIImageViewに、ボーダーをつけたい場合、以下のような関数をつくります。

extension UIImageView {
  func cropAsCircleWithBorder(borderColor : UIColor, strokeWidth: CGFloat) {
    var radius = min(self.bounds.width, self.bounds.height)
    var drawingRect : CGRect = self.bounds
    drawingRect.size.width = radius
    drawingRect.origin.x = (self.bounds.size.width - radius) / 2
    drawingRect.size.height = radius
    drawingRect.origin.y = (self.bounds.size.height - radius) / 2

    radius /= 2

    var path = UIBezierPath(roundedRect: CGRectInset(drawingRect, strokeWidth/2, strokeWidth/2), cornerRadius: radius)
    let border = CAShapeLayer()
    border.fillColor = UIColor.clearColor().CGColor
    border.path = path.CGPath
    border.strokeColor = borderColor.CGColor
    border.lineWidth = strokeWidth
    self.layer.addSublayer(border)

    path = UIBezierPath(roundedRect: drawingRect, cornerRadius: radius)
    let mask = CAShapeLayer()
    mask.path = path.CGPath
    self.layer.mask = mask
  }
}

つかいかた

imageView.cropAsCircleWithBorder(UIColor.whiteColor(), strokeWidth: 1)
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6