2012-12-10 46 views
1

我在我的應用程序中實現了一個標籤系統,爲了實現這一點,我需要標籤和文本的背景圖像來覆蓋該圖像。問題是 - 我怎樣才能將圖像拉伸以適應文字? 「數學」運作良好,但像「經濟學」這樣的詞不會與背景圖像重疊。如何拉伸UIImage以適應文字?

這就是我的標籤是這樣的:

回答

1

您首先需要計算文本的預期大小,然後相應地爲框架指定圖像。如果需要,您可以使用帶有寬度和高度的圖像。這是代碼片段。

CGSize maximumLabelSize = CGSizeMake(600,52); // maximum possible size 
    CGSize expectedLabelSize = [brandName sizeWithFont:[UIFont fontWithName: @"Helvetica-Bold" size:20] 
            constrainedToSize:maximumLabelSize 
             lineBreakMode:UILineBreakModeTailTruncation]; 

    UIImage *centerStretchedImage =[[UIImage imageNamed:@"yourImage.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0]; 

    CGRect frame = CGRectMake(x, y, expectedLabelSize.width+20,52); 
    UIImageView *dynamicImage = [[UIImageView alloc] initWithFrame:frame]; 
    dynamciImage.image = centerStretchedImage; 
1

我最好的猜測是使用拉伸圖片,這些都是讓您設定的iOS可以舒展部分只是普通的圖像。

這些圖像是很容易的:

UIImage *imageTemp = [UIImage imageNamed:@"ButtonBackground.png"]; 

// For iOS 4.3 and lower 
UIImage *stretchableImage = [imageTemp stretchableImageWithLeftCapWidth:20 topCapHeight:10]; 

// if you are targetting iOS 5 and higher 
UIImage *stretchableImage = [imageTemp resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 20, 20)]; 

2010只是舉例來說,他們可能是你的圖像不同。如果這些是UIButton,您可以將可拉伸圖像設置爲按鈕的背景,並且該按鈕將正確增長。如果您將代碼中的文本設置爲UILabel,則可以使用sizeWithFont:constrainedToSize:來計算字符串的字符。然後設置圖像的正確大小。

+0

從[蘋果DOC(http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/DeprecationAppendix/AppendixADeprecatedAPI.html#//apple_ref/occ/instm/UIViewController/viewDidUnload)_stretchableImageWithLeftCapWidth:創建並返回一個帶有指定頂點值的新圖像對象。 (在iOS 5.0中不推薦使用,不要使用resizableImageWithCapInsets:指定cap insets,使內部爲1x1區域。)_ – iDev

+0

是的,你是正確的,但是如果你的目標是iOS 4.3,你也可以使用'stretchableImageWithLeftCapWidth: topCapHeight:'。 – rckoenes

+0

是的,只有我們的目標是iOS 4.3以上。對於iOS 5.0以上版本,這已被棄用。 – iDev

1

您可以找到字符串寬度(可能的UILabel你的情況),像下面

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
         constrainedToSize:maximumLabelSize 
         lineBreakMode:yourLabel.lineBreakMode]; 

一旦文本長度是已知的,您可以使用,並設置爲背景圖片拉伸。

UIImage *strechableImage = [[UIImage imageNamed:@"tagImage"] resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 25)] 

的插圖(CAPS)是(頂部,左邊,底部,頂部)和限定了不進行縮放/拉伸(例如圓角)的區域。

從蘋果文檔

在縮放或圖像的大小調整,由蓋所覆蓋的區域不進行縮放或調整大小。相反,在每個方向上未被帽覆蓋的像素區域是平鋪的,從左到右和從上到下來調整圖像的大小。