How to round corners of UIImage with Hexagon mask

前端 未结 4 1512
轻奢々
轻奢々 2020-11-28 10:21

I\'m trying to add a hexagon mask to a UIImage which I has been successful in. However I am unable to round the sides of the hexagon mask. I thought adding cell.profilePic.l

4条回答
  •  离开以前
    2020-11-28 10:54

    Here is the swift 3 version of Rob's answer.

        let lineWidth: CGFloat = 5.0
        let path = UIBezierPath(roundedPolygonPathWithRect: self.bounds, lineWidth: lineWidth, sides: 6, cornerRadius: 12)
    
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        mask.lineWidth = lineWidth
        mask.strokeColor = UIColor.clear.cgColor
        mask.fillColor = UIColor.white.cgColor
        self.layer.mask = mask
    
        let border = CAShapeLayer()
        border.path = path.cgPath
        border.lineWidth = lineWidth
        border.strokeColor = UIColor.black.cgColor
        border.fillColor = UIColor.clear.cgColor
        self.layer.addSublayer(border)
    
    extension UIBezierPath {
    
        convenience init(roundedPolygonPathWithRect rect: CGRect, lineWidth: CGFloat, sides: NSInteger, cornerRadius: CGFloat) {
    
            self.init()
    
            let theta = CGFloat(2.0 * M_PI) / CGFloat(sides)
            let offSet = CGFloat(cornerRadius) / CGFloat(tan(theta/2.0))
            let squareWidth = min(rect.size.width, rect.size.height)
    
            var length = squareWidth - lineWidth
    
            if sides%4 != 0 {
                length = length * CGFloat(cos(theta / 2.0)) + offSet/2.0
            }
            let sideLength = length * CGFloat(tan(theta / 2.0))
    
            var point = CGPoint(x: squareWidth / 2.0 + sideLength / 2.0 - offSet, y: squareWidth - (squareWidth - length) / 2.0)
            var angle = CGFloat(M_PI)
            move(to: point)
    
            for _ in 0 ..< sides {
                point = CGPoint(x: point.x + CGFloat(sideLength - offSet * 2.0) * CGFloat(cos(angle)), y: point.y + CGFloat(sideLength - offSet * 2.0) * CGFloat(sin(angle)))
                addLine(to: point)
    
                let center = CGPoint(x: point.x + cornerRadius * CGFloat(cos(angle + CGFloat(M_PI_2))), y: point.y + cornerRadius * CGFloat(sin(angle + CGFloat(M_PI_2))))
                addArc(withCenter: center, radius:CGFloat(cornerRadius), startAngle:angle - CGFloat(M_PI_2), endAngle:angle + theta - CGFloat(M_PI_2), clockwise:true)
    
                point = currentPoint // we don't have to calculate where the arc ended ... UIBezierPath did that for us
                angle += theta
            }
    
            close()
        }
    }
    

提交回复
热议问题