Bezier路径的基本UIImageView蒙版形状

时间:2017-04-25 19:02:12

标签: ios swift drawing

我想让个人资料照片看起来像这张照片。 我正在试验UIBezierPaths(),我相信它们是我最好的选择。

enter image description here

我也是iOS绘图的新手,但到目前为止,我已经能够实现这种形状:

enter image description here 对于我能够学到的东西。代码:

extension UIImage {
    class func shapeImageWithBezierPath(bezierPath: UIBezierPath, fillColor: UIColor?, strokeColor: UIColor?, strokeWidth: CGFloat = 0.0) -> UIImage! {
        //: Normalize bezier path. We will apply a transform to our bezier path to ensure that it's placed at the coordinate axis. Then we can get its size.
        bezierPath.apply(CGAffineTransform(translationX: -bezierPath.bounds.origin.x, y: -bezierPath.bounds.origin.y))
        let size = CGSize(width: bezierPath.bounds.size.width, height: bezierPath.bounds.size.height)

        //: Initialize an image context with our bezier path normalized shape and save current context
        UIGraphicsBeginImageContext(size)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        context.saveGState()

        //: Set path
        context.addPath(bezierPath.cgPath)
        //: Set parameters and draw
        if strokeColor != nil {
            strokeColor!.setStroke()
            context.setLineWidth(strokeWidth)
        } else { UIColor.clear.setStroke() }
        fillColor?.setFill()
        context.drawPath(using: .fillStroke)

        //: Get the image from the current image context
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //: Restore context and close everything
        context.restoreGState()
        UIGraphicsEndImageContext()
        //: Return image
        return image
    }
}


  let circleShapePath = UIBezierPath()
circleShapePath.move(to: CGPoint(x: 50, y: 0))
circleShapePath.addLine(to: CGPoint(x: 100, y: 0))
circleShapePath.addLine(to: CGPoint(x: 100, y: 100))
circleShapePath.close()

let newCircle = UIImage.shapeImageWithBezierPath(bezierPath: cirleShapePath, fillColor: .red, strokeColor: .white, strokeWidth: 5)

我的麻烦一直是找到一个正确的方法来连接左上角和下点与曲线,并将其桅杆连接到UIImageview。

谢谢!

1 个答案:

答案 0 :(得分:0)

使用此网站生成所需的形状,然后将代码(您可能需要根据Swift版本修改语法)复制到项目中: http://www.radicalphase.com/bezierpath/