1

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)

    CGContextBeginPath(context);

    UIColor.blackColor().set()

    for path in paths{
        path.stroke()
    }

    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!

pkamb
  • 33,281
  • 23
  • 160
  • 191
Jonas
  • 2,139
  • 17
  • 38

1 Answers1

1

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 {
        path.stroke()
    }
    let image = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return image
}
rjpadula
  • 944
  • 7
  • 7
  • Thanks for your reply. I found another solution to my problem but I guess your code works too. I will accept it as the right answer. – Jonas Sep 12 '16 at 17:24
  • I am sorry to say that this is not the exactly right answer, it can just draw part of the UIBezierPath array for me, if I enlarge image width and height, it will be right, btw can you share your solution.? – newszer Jun 28 '18 at 08:45
  • @JonasSchafft please post your "another solution to my problem" as an Answer. – pkamb May 18 '19 at 18:20