IOS拉伸之底蓋設定

2022-02-18 18:39:19 字數 2647 閱讀 6283

1.選定拉伸

uiimageview *fieldimage=[[uiimageviewalloc]initwithframe:cgrectmake(37,48+35,240, 32)];

fieldimage.userinteractionenabled=yes;

fieldimage.contentstretch=cgrectmake(0,0.4, 1, 0.5);

fieldimage.image=[uiimageimagenamed:@"輸入框"];

[self.viewaddsubview:fieldimage];

2.拉伸技巧

此按鈕: button.png,尺寸為:24x60

現在我們把它用作為按鈕背景,按鈕尺寸是150x50:

// 得到view的尺寸 

cgsize viewsize = self.view.bounds.size;

// 初始化按鈕 uibutton *button = [[uibutton alloc] init]; 

// 設定尺寸 button.bounds = cgrectmake(0, 0, 150, 50); 

// 設定位置 button.center = cgpointmake(viewsize.width * 0.5f, viewsize.height * 0.5f); 

// 載入 uiimage *image = [uiimage imagenamed:@"button"]; 

// 設定背景 [button setbackgroundimage:image forstate:uicontrolstatenormal]; 

// 新增按鈕 [self.view addsubview:button];

執行效果圖:

可以看到,效果非常地差。原因很簡單,因為原圖大小為24x60,現在整張被全方位拉伸為150x50,比較嚴重的是的4個角。

有些人可能馬上想到乙個解決方案,你叫美工把做大一點不就好了麼,怎麼拉伸都沒事。沒錯,這是一種解決方案,不過不建議採取。原因很簡單:1.大,導致安裝包也大,載入到記憶體中也大;2.有更好的解決方案。

細看一下,其實會變得難看,完全是因為4個角被拉伸了,中間的拉伸並沒有明顯地醜化外觀。因此要想小被拉伸後不會變得難看,在拉伸的時候,我們只需拉伸的中間一塊矩形區域即可,不要拉伸邊緣部分。

比如只拉伸下圖的矩形區域,上下左右的邊緣都不拉伸:

ios中提供很好用的api幫我們實現上述功能。到ios 6.0為止,ios提供了3種拉伸的解決方案,接下來分別詳細介紹這些方案。

一、ios 5.0之前

ios中有個叫端蓋(end cap)的概念,用來指定中的哪一部分不用拉伸。比如下圖中,黑色代表需要被拉伸的矩形區域,上下左右不需要被拉伸的邊緣就稱為端蓋。

使用uiimage的這個方法,可以通過設定端蓋寬度返回乙個經過拉伸處理的uiimage物件

- (uiimage *)stretchableimagewithleftcapwidth:(nsinteger)leftcapwidth topcapheight:(nsinteger)topcapheight;

這個方法只有2個引數,leftcapwidth代表左端蓋寬度,topcapheight代表頂端蓋高度。系統會自動計算出右端蓋寬度(rightcapwidth)和底端蓋高度(bottomcapwidth),演算法如下:

// width為寬度 rightcapwidth = width - leftcapwidth - 1; // height為高度 topcapheight = height - topcapheight - 1

經過計算,你會發現中間的可拉伸區域只有1x1

// stretchwidth為中間可拉伸區域的寬度 stretchwidth = width - leftcapwidth - rightcapwidth = 1; // stretchheight為中間可拉伸區域的高度 stretchheight = height - topcapheight - bottomcapheight = 1;

因此,使用這個方法只會拉伸中間1x1的區域,並不會影響到邊緣和角落。

下面演示下方法的使用:

// 左端蓋寬度 nsinteger leftcapwidth = image.size.width * 0.5f; // 頂端蓋高度 nsinteger topcapheight = image.size.height * 0.5f; // 重新賦值 image = [image stretchableimagewithleftcapwidth:leftcapwidth topcapheight:topcapheight];

呼叫這個方法後,原來的image並不會發生改變,會產生乙個新的經過拉伸的uiimage,所以第6行中需要將返回值賦值回給image變數

執行效果:

可以發現,非常美觀地顯示出來了

注意:1.這個方法在ios 5.0出來後就過期了

2.這個方法只能拉伸1x1的區域

二、ios 5.0

iOS開發之應用設定

ios 8之後,應用啟動的時候隱藏狀態列 targets general deploymentinfo hide status bar打勾 應用啟動完成後,狀態列會重新自動顯示 ios 8之前,應用啟動的時候隱藏狀態列 應用啟動後,狀態列不會自動重新顯示,需要手動顯示 ios 8之前少一張啟動怎麼辦...

iOS之UITableView設定全屏分隔線

首先系統的分隔線有以下幾種tableview.separatorstyle uitableviewcellseparatorstylenone uitableviewcellseparatorstylenone 隱藏系統分隔線 uitableviewcellseparatorstylesinglel...

iOS之UITableView設定全屏分隔線

首先系統的分隔線有以下幾種tableview.separatorstyle uitableviewcellseparatorstylenone uitableviewcellseparatorstylenone 隱藏系統分隔線 uitableviewcellseparatorstylesinglel...