Jonas Schafft Jonas Schafft - 1 year ago 115
iOS Question

Create an UIImage from Uibezierpath Array in Swift

I want to create an UIImage from an Array of multiple UIBezierPaths in Swift.

I tried the following code:

func convertPathsToImage(paths: [UIBezierPath]) -> UIImage{

let imageWidth: CGFloat = 200
let imageHeight: CGFloat = 200

let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()!
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(nil, Int(imageWidth), Int(imageHeight), 8, 0, colorSpace, bitmapInfo.rawValue)



for path in paths{

let newImageRef = CGBitmapContextCreateImage(context);
let newImage = UIImage(CGImage: newImageRef!)

return newImage


The Result is an empty image.

Can someone explain me what i`m doing wrong? Thank you very much!

Answer Source

I can't tell you what you are doing wrong, but I had a similar issue, and this code works for me.

func convertPathsToImage(paths: [UIBezierPath]) -> UIImage
    let imageWidth: CGFloat = 200
    let imageHeight: CGFloat  = 200
    let strokeColor:UIColor = UIColor.blackColor()

    // Make a graphics context
    UIGraphicsBeginImageContextWithOptions(CGSize(width: imageWidth, height: imageHeight), false, 0.0)
    let context = UIGraphicsGetCurrentContext()

    CGContextSetStrokeColorWithColor(context, strokeColor.CGColor)

    for path in paths {
    let image = UIGraphicsGetImageFromCurrentImageContext()


    return image
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download