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?
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
}
}