設計稿常會要求「背景框 + 圖示 + 右側箭頭」這種組合的按鈕。與其請設計師切成一整張圖,不如在程式碼裡把三層影像合成一張,再交給 UIButton 使用。做法是自己寫一個回傳 UIImage 的方法。
renderInContext: 把整個容器渲染進去。- (UIImage *)getOneImageButtonWithArrow {
// 1. 暫存容器
UIView *tmpView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 38.0f, 32.0f)];
tmpView.backgroundColor = [UIColor clearColor];
// 2. 背景圖
UIImage *bgImg = [UIImage imageNamed:@"background.png"];
UIImageView *bgImageView = [[UIImageView alloc] initWithImage:bgImg];
bgImageView.frame = tmpView.frame;
[tmpView addSubview:bgImageView];
// 3. 中央圖示
UIImageView *tmpImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon.png"]];
tmpImageView.frame = CGRectMake(4.0f, 4.0f, 24.0f, 24.0f);
tmpImageView.backgroundColor = [UIColor clearColor];
tmpImageView.alpha = 1.0f;
[tmpView addSubview:tmpImageView];
// 4. 右側箭頭
UIImageView *arrowImageView =
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]];
arrowImageView.frame = CGRectMake(28.0f, 4.0f, 6.0f, 24.0f);
[tmpView addSubview:arrowImageView];
// 5. 渲染成圖
UIGraphicsBeginImageContextWithOptions(tmpView.bounds.size, NO, 0.0);
[tmpView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *tmpImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tmpImage;
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[self getOneImageButtonWithArrow] forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 38, 32);
[self.view addSubview:button];
[bgImageView release];。