您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS UI 篇:Quartz2D 實作信紙條紋背景

編輯:iOS 相關資訊

本篇示範如何運用 Quartz2D 繪圖與「模式填色」技巧,做出信紙般的橫線條紋背景,並進一步完成一個簡陋的電子書閱讀器。

一、前導:圖片平鋪

先建立一個專案,在主控制器中實作以下程式碼,就能輕鬆讓一張圖片在 view 中平鋪鋪滿:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage *image = [UIImage imageNamed:@"me"];
    UIColor *color = [UIColor colorWithPatternImage:image];
    self.view.backgroundColor = color;
}

colorWithPatternImage: 會把一張小圖當作「填色模式」重複平鋪,是實現條紋背景的關鍵。

二、實作信紙條紋

預設的 view 沒有分割線,加上分割線有兩種方式:

  1. 請美工做一張專門的背景圖。缺點是信的長度不確定,背景圖長度也難拿捏。
  2. 用一張小圖建立填色模式來平鋪,更靈活——這裡採用此法。

步驟:先畫出要平鋪的小圖(畫矩形 + 畫線條),再從上下文取出圖片設為背景。

- (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 翻頁動畫,就能打造出具備紙張質感的閱讀體驗。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved