本篇示範如何運用 Quartz2D 繪圖與「模式填色」技巧,做出信紙般的橫線條紋背景,並進一步完成一個簡陋的電子書閱讀器。
先建立一個專案,在主控制器中實作以下程式碼,就能輕鬆讓一張圖片在 view 中平鋪鋪滿:
- (void)viewDidLoad
{
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:@"me"];
UIColor *color = [UIColor colorWithPatternImage:image];
self.view.backgroundColor = color;
}
colorWithPatternImage: 會把一張小圖當作「填色模式」重複平鋪,是實現條紋背景的關鍵。
預設的 view 沒有分割線,加上分割線有兩種方式:
步驟:先畫出要平鋪的小圖(畫矩形 + 畫線條),再從上下文取出圖片設為背景。
- (void)viewDidLoad
{
[super viewDidLoad];
// 1. 建立一張用於平鋪的小圖片
CGSize size = CGSizeMake(self.view.frame.size.width, 35);
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
// 2. 畫矩形底色
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat height = 35;
CGContextAddRect(ctx, CGRectMake(0, 0, self.view.frame.size.width, height));
[[UIColor whiteColor] set];
CGContextFillPath(ctx);
// 3. 畫線條
CGFloat lineWidth = 2;
CGFloat lineY = height - lineWidth;
CGContextMoveToPoint(ctx, 0, lineY);
CGContextAddLineToPoint(ctx, 320, lineY);
[[UIColor blackColor] set];
CGContextStrokePath(ctx);
// 4. 取出圖片並設為平鋪背景
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIColor *color = [UIColor colorWithPatternImage:image];
self.view.backgroundColor = color;
}
提醒:若未特別設定,透明區域會顯示為黑色,記得先鋪好底色。
把上述條紋背景設到 UITextView 上,再加上翻頁按鈕與 pageCurl 轉場動畫,就是一個簡單的閱讀器:
- (IBAction)perBtnClick:(UIButton *)sender {
self.index--;
self.textview.text = [NSString stringWithFormat:@"第%d頁", self.index];
CATransition *ca = [[CATransition alloc] init];
ca.type = @"pageCurl";
[self.textview.layer addAnimation:ca forKey:nil];
}
- (IBAction)nextBtnClick:(UIButton *)sender {
self.index++;
self.textview.text = [NSString stringWithFormat:@"第%d頁", self.index];
CATransition *ca = [[CATransition alloc] init];
ca.type = @"pageCurl";
[self.textview.layer addAnimation:ca forKey:nil];
}
透過 Quartz2D 手繪條紋、colorWithPatternImage 平鋪,再搭配 pageCurl 翻頁動畫,就能打造出具備紙張質感的閱讀體驗。