Rounding UIImage and adding a border

前端 未结 9 1053
青春惊慌失措
青春惊慌失措 2020-12-09 18:19

so I want to show some pictures as annotations on the map. In order to do that I need to add the image property of the MKAnnotationView. I\'m using the regular images but I

9条回答
  •  有刺的猬
    2020-12-09 18:28

    Use this extension to 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
    }
    

    Usage :

            self.circleView.cropAsCircleWithBorder(UIColor.redColor(), strokeWidth: 20)
    

    Result :

提交回复
热议问题