我現(xiàn)在正在努力地編寫那本關(guān)于 UIKit / Quartz 的書,書中描述了很多使用 Bezier 路徑繪圖的案例。今天,在進(jìn)行了一天忙碌的寫作之后,我現(xiàn)在決定好好休息、放松一下。
因此我登上了 IRC (Internet Relay Chat),在那里我遇到了一個很有意思的挑戰(zhàn)。它是以 Clarus the dog cow 的形式出現(xiàn)的(譯者注:一只像牛的狗,這個卡通形象由蘋果傳奇圖形設(shè)計師 SusanKare 設(shè)計,在早期的 Mac 系統(tǒng)中,用來顯示打印頁面的朝向)。這只狗狗是以點陣圖 (bitmap) 的形式出現(xiàn)的,通常情況下將其轉(zhuǎn)換為 UIImage
并不是一件很容易的事。當(dāng)然我覺得,應(yīng)該有一種通用的方法能夠?qū)⑵滢D(zhuǎn)換為可重復(fù)使用的路徑。
而今,受到我對 PaintCode 的評論的啟示,我決定創(chuàng)建一個通用的「點陣圖→Bezier 路徑」方法來解決這個問題。我最終將會得到一個擴(kuò)展類 (Category),能夠?qū)⒆止?jié)轉(zhuǎn)換為易于繪制的 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;}
譯者注
評論中有人提問:如何將這個點陣圖轉(zhuǎn)換為 NSData
對象呢?
Clarus 的點陣圖代碼可以在這里找到:https://gist.github.com/erica/5224282