要在 iPhone 上畫出圓角矩形(例如做一個亮度調整器的圖示),核心是三件事:建立一塊 bitmap 繪圖環境、把圓角矩形路徑加到 context 上、再填色並轉成 UIImage。以下程式碼改寫自 Apple 的範例。
@implementation BrightnessController
// MyCreateBitmapContext: Source based on Apple Sample Code
CGContextRef MyCreateBitmapContext (int pixelsWide, int pixelsHigh)
{
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void *bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc(bitmapByteCount);
if (bitmapData == NULL)
{
fprintf(stderr, "Memory not allocated!");
CGColorSpaceRelease(colorSpace);
return NULL;
}
context = CGBitmapContextCreate(bitmapData,
pixelsWide,
pixelsHigh,
8,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if (context == NULL)
{
free(bitmapData);
fprintf(stderr, "Context not created!");
return NULL;
}
CGColorSpaceRelease(colorSpace);
return context;
}
這裡有兩個容易忽略的細節。一是每像素 4 bytes(RGBA),因此 bitmapBytesPerRow 是寬度乘 4,而總位元組數是「每行位元組數 × 高度」,不是寬度乘高度。二是 colorspace 用完就必須 CGColorSpaceRelease,而 bitmapData 在所有失敗路徑上都要記得 free,否則就是洩漏。
// addRoundedRectToPath: Source based on Apple Sample Code
static void addRoundedRectToPath(CGContextRef context, CGRect rect,
float ovalWidth, float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM(context, ovalWidth, ovalHeight);
fw = CGRectGetWidth(rect) / ovalWidth;
fh = CGRectGetHeight(rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2); // 從右下開始
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1); // 右上角
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // 左上角
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // 左下角
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // 回到右下
CGContextClosePath(context);
CGContextRestoreGState(context);
}
這個技巧很聰明:透過 CGContextScaleCTM 把座標系縮放,就能用單位圓弧拼出圓角,而不必自己算一堆三角函數。SaveGState / RestoreGState 成對出現,確保這次變形不會污染後續繪製——這一步在很多自製的複製貼上程式碼裡會被漏掉,接著就會出現莫名的位移。
// Build an image tinted at the given percentage
id createImage(float percentage)
{
CGContextRef context = MyCreateBitmapContext(30, 30);
addRoundedRectToPath(context, CGRectMake(0.0f, 0.0f, 30.0f, 30.0f), 4.0f, 4.0f);
CGFloat gray[4] = {percentage, percentage, percentage, 1.0f};
CGContextSetFillColor(context, gray);
CGContextFillPath(context);
CGImageRef myRef = CGBitmapContextCreateImage(context);
free(CGBitmapContextGetData(context));
CGContextRelease(context);
return [UIImage imageWithCGImage:myRef];
}
注意 CGBitmapContextCreateImage 建立的 CGImage 沒有被 release,在 MRC 下會洩漏;實務上應該搭配 CGImageRelease(myRef),或改用 ARC 下的橋接寫法。這裡保留原樣以便對照,套用時記得補上。
#define MAXDEPTH 8
-(BrightnessController *) initWithBrightness: (int) aBrightness
{
self = [super init];
brightness = aBrightness;
self.title = [NSString stringWithFormat:@"%d%%", brightness * 10];
[self.tabBarItem initWithTitle:self.title
image:createImage(((float) brightness / 10.0f))
tag:0];
return self;
}
- (void)loadView
{
UIView *contentView = [[UIView alloc] init];
float percent = brightness * 0.1;
contentView.backgroundColor =
[UIColor colorWithRed:percent green:percent blue:percent alpha:1.0];
contentView.autoresizesSubviews = YES;
contentView.autoresizingMask =
(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.view = contentView;
[contentView release];
}
整體效果是:每個 tab 的圖示是一塊灰階圓角方塊,灰階深淺對應各自的亮度值,而該頁的背景色也同步變暗或變亮,兩者互相呼應。
摘自 volcan1987的專欄