I’m working hard on my UIKit / Quartz book, where I’m doing a lot of coverage of drawing using Bezier paths. Today, after a pretty detail-oriented day of writing, I was more than ready to take a break.
I headed over to IRC and encountered a particularly interesting challenge. It came in the form of Clarus the dog cow. She’s normally a bitmap, which isn’t something that translates particularly well into the world of UIImages. Surely, I thought, there should be a way to generalize her to a reusable path.
Inspired by my PaintCode write-up from today, I decided to create a generalized bitmap-to-Bezier path method to address this. What I ended up with is a category that transforms bytes into an easy-to-draw UIBezierPath.
@implementation UIBezierPath (BitmapExtension) + (UIBezierPath *) pathFromBitmap: (NSData *) data size: (CGSize) size { Byte *bytes = (Byte *) data.bytes; CFIndex height = size.height; CFIndex width = size.width; if (height * width != data.length) { NSLog(@"Error: size does not match data's available bytes"); return nil; } UIBezierPath *bezierPath = [UIBezierPath bezierPath]; for (CFIndex y = 0; y < height; y++) { for (CFIndex x = 0; x < width; x++) { CFIndex index = y * width + x; if (bytes[index] != 0) { UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(x, y, 1, 1)]; [bezierPath appendPath:path]; } } } return bezierPath; }
2 Comments
This is a handy little method. Question, though: How did you get Clarus into an NSData object?
Since you ask: https://gist.github.com/erica/5224282 🙂