您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 在 UIButton 內合成自定義箭頭圖示

編輯:iOS 開發綜合

設計稿常會要求「背景框 + 圖示 + 右側箭頭」這種組合的按鈕。與其請設計師切成一整張圖,不如在程式碼裡把三層影像合成一張,再交給 UIButton 使用。做法是自己寫一個回傳 UIImage 的方法。

合成思路

  1. 建立一個透明的暫存容器 View,尺寸就是最終按鈕的大小。
  2. 依序把背景圖、中央圖示、箭頭圖疊上去,各自指定 frame。
  3. 開啟圖形上下文,用 renderInContext: 把整個容器渲染進去。
  4. 取出 UIImage,關閉上下文並回傳。

程式碼

- (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];

幾點提醒

  • 原範例使用 MRC 寫法(手動 release),在 ARC 專案中請直接移除 [bgImageView release];。
  • 若箭頭方向或圖示位置會依狀態改變,建議把座標抽成參數,或傳入一個描述配置的 struct,避免寫出多個幾乎一樣的方法。
  • 這個合成的結果是靜態圖,無法再動態替換其中的圖示。若需要頻繁變換內容,改用「UIView 容器 + 三個 UIImageView」並直接加入視圖,會比每次重新合成更划算。
  • 箭頭這類簡單幾何圖形,也可以直接用 Core Graphics 畫出來,省下切圖成本並支援任意解析度。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved