2016-09-12 7 views
1

Ich möchte ein UIImage aus einem Array von mehreren UIBezierPaths in Swift erstellen.Erstellen Sie ein UIImage aus Uibezierpath-Array in Swift

Ich habe versucht, den folgenden 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 

    } 

Das Ergebnis ist ein leeres Bild.

Kann mir jemand erklären, was ich falsch mache? Vielen Dank!

+0

Fügen Sie diese Pfade zum Layer der Ansicht hinzu? – EridB

+0

@EridB Nein. Ich möchte sie nicht zum Layer der Ansicht hinzufügen –

+0

Kannst du bitte ein konkretes Beispiel für '[UIBezierPath]' Array anfügen? –

Antwort

1

Ich kann Ihnen nicht sagen, was Sie falsch machen, aber ich hatte ein ähnliches Problem, und dieser Code funktioniert für mich.

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 
} 
+0

Danke für Ihre Antwort. Ich habe eine andere Lösung für mein Problem gefunden, aber ich denke, dass Ihr Code auch funktioniert. Ich werde es als die richtige Antwort akzeptieren. –