如何使用可伸缩图像创建UIImageView

时间:2013-07-24 15:37:32

标签: iphone ios uiimage

在我的应用中,一个要求是将标签的背景设置为某个图像。我已经通过此代码

在UIlabel后面设置图像来完成它

.H文件

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    UIImageView *lblBGIV;
} 
@end

.M文件

- (void)viewDidLoad
{
    [super viewDidLoad];

    lblBGIV = [[UIImageView alloc] init];

    UIImage *lblBGImg = [[UIImage imageNamed:@"textlblbg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 8, 0, 8)];

    lblBGIV.image = lblBGImg;
}

- (void)updateLabelMethod:(NSTimer *)theTimer {

            lblBGIV.frame = CGRectMake(label.frame.origin.x-9, label.frame.origin.y-5, label.frame.size.width+18, 26);

            [self.myScrollView addSubview:lblBGIV];
            [self.myScrollView sendSubviewToBack:lblBGIV];
}

3 个答案:

答案 0 :(得分:8)

您必须为不同的iOS设置不同的代码来设置图像。使用此代码,

UIImage *lblBGImg;
    float currentVersion = 6.0;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= currentVersion)
    {
        //device have iOS 6 or above
        lblBGImg = [[UIImage imageNamed:@"textlblbg41.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 15, 0, 15)  resizingMode:UIImageResizingModeStretch];
    }else{
        //device have iOS 5.1 or belove
        lblBGImg = [[UIImage imageNamed: @"textlblbg41.png"] stretchableImageWithLeftCapWidth:15.0 topCapHeight:15.0];
    }
    lblBGIV.image = lblBGImg;

这将成为iOS的诀窍。

答案 1 :(得分:5)

改为使用resizableImageWithCapInsets:resizingMode:

UIImage *lblBGImg = [[UIImage imageNamed:@"textlblbg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 8, 0, 8) resizingMode:UIImageResizingModeStretch];

答案 2 :(得分:0)

迅速:

UIImage(named: "videoSliderFiller")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .stretch)