ios - 带有贝塞尔路径的基本 UIImageView 蒙版形状

标签 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 的正确方法。

谢谢!

最佳答案

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

关于ios - 带有贝塞尔路径的基本 UIImageView 蒙版形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43618908/

相关文章:

objective-c - iOS - GANTracker 没有什么可调度的

ios - iPhone 7 Plus AVPlayer 周围有边框(白色颜色不匹配)

html - 用文本填充 Canvas 形状

ios - 在 iOS 上组合相交的 CGPath

ios - 如何在加载数据后安全地解包 TableView 单元格

iOS 使用 vImage - 加速将 QCAR YUV 转换为 RGB

ios - XCUITest如何访问tableView表头

ios - View 层次结构错误 - 试图在新 Storyboard中打开新 View Controller

ios - SwiftUI:如何在按钮单击+ API 调用后显示下一个 View

java - Android - 从 Assets 中绘制图像,发生了一些奇怪的事情