How to create a UIImage with UIBezierPath

前端 未结 7 855
南旧
南旧 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

    https://stackoverflow.com/a/17408397/3191351 Translated Into Swift

    import UIKit
    
    extension UIBezierPath {
    
        /** Returns an image of the path drawn using a stroke */
        func strokeImageWithColor(var strokeColor: UIColor?,var fillColor: UIColor?) -> UIImage {
    
            // get your bounds
            let bounds: CGRect = self.bounds
    
            UIGraphicsBeginImageContextWithOptions(CGSizeMake(bounds.size.width + self.lineWidth * 2, bounds.size.width + self.lineWidth * 2), false, UIScreen.mainScreen().scale)
    
            // get reference to the graphics context
            let reference: CGContextRef = UIGraphicsGetCurrentContext()!
    
            // translate matrix so that path will be centered in bounds
            CGContextTranslateCTM(reference, self.lineWidth, self.lineWidth)
    
            if strokeColor == nil {
                strokeColor = fillColor!;
            }
            else if fillColor == nil {
                fillColor = strokeColor!;
            }
    
            // set the color
            fillColor?.setFill()
            strokeColor?.setStroke()
    
            // draw the path
            fill()
            stroke()
    
    
            // grab an image of the context
            let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    
            UIGraphicsEndImageContext()
    
            return image
        }
    
    }
    

提交回复
热议问题