iOS圖片展開,ios展開

來源:互聯網
上載者:User

iOS圖片展開,ios展開

假如下面的一張圖片,是用來做按鈕的背景圖片的,原始大小是76 × 40

我們通過代碼將這張圖片設定為按鈕的背景圖片,假如我們將建立好的按鈕的寬高設定為:(W=200, H=50)代碼如下:

    // 初始化按鈕    UIButton *button = [[UIButton alloc] init];    // 設定尺寸    button.frame = CGRectMake(100, 200, 200, 50);        // 載入圖片    UIImage *image = [UIImage imageNamed:@"ppm_new_shuliang.png"];        // 設定背景圖片    [button setBackgroundImage:image forState:UIControlStateNormal];        // 添加按鈕      [self.view addSubview:button];

 結果如下:圖片被展開了。

 

原因分析:是將原是尺寸為76 × 40 的圖片展開成了W=200, H=50;
解決方案:
1.找美工重做一張較大的圖片,這樣的話就會出現軟體包將來會變大,佔用空間更大;如果我們要經常修改按鈕的frame,美工設計比較繁瑣;
2.蘋果為我們提供了關於圖片展開的API,我們可以直接利用代碼實現;

修改後:

    // 初始化按鈕    UIButton *button = [[UIButton alloc] init];    // 設定尺寸    button.frame = CGRectMake(100, 200, 200, 50);        CGFloat top = 0; // 頂端蓋高度    CGFloat bottom = 0 ; // 底端蓋高度    CGFloat left = 22; // 左端蓋寬度    CGFloat right = 22; // 右端蓋寬度    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);            // 載入圖片    UIImage *image = [UIImage imageNamed:@"ppm_new_shuliang.png"];        image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];        // 設定背景圖片    [button setBackgroundImage:image forState:UIControlStateNormal];        // 添加按鈕      [self.view addSubview:button];

 

 

 

還有一種設定方法:

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.