How to create a UIImage with UIBezierPath

前端 未结 7 854
南旧
南旧 2020-12-09 06:02

I wrote some code to create a UIImage with UIBezierPath but it didn\'t work.

Can someone help me find out what\'s wrong with my code?

7条回答
  •  有刺的猬
    2020-12-09 06:14

    extension UIBezierPath {
        func shapeImage(view: UIView) -> UIImage! {
    
        // begin graphics context for drawing
        UIGraphicsBeginImageContextWithOptions(view.frame.size, false, UIScreen.main.scale)
    
        // configure the view to render in the graphics context
        //view.layer.render(in: UIGraphicsGetCurrentContext()!)
    
        // get reference to the graphics context
        let context = UIGraphicsGetCurrentContext()
    
        // translate matrix so that path will be centered in bounds
        context?.translateBy(x: -(bounds.origin.x - self.lineWidth), y: -(bounds.origin.y - self.lineWidth))
        // set color
        UIColor.black.setStroke()
    
        // draw the stroke
        stroke()
    
        // get an image of the graphics context
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    
        // end the context
        UIGraphicsEndImageContext()
    
        return image
        }
    }
    

    first view with Bezier

    second - bezier transformed to image

提交回复
热议问题