zoukankan      html  css  js  c++  java
  • ios UIImage图片拉伸 resizableImageWithCapInsets:

    常见的按钮添加和背景设置如下:

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(80, 130, 160, 44)];
    [button setTitle:@”Test Button” forState:UIControlStateNormal];

    // Image with without cap insets
    UIImage *buttonImage = [UIImage imageNamed:@”blueButton”];

    [button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];
    [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [[self view] addSubview:button];
    [/crayon]

    所得到的按钮会相当悲剧…

    iOS5中提供了一个新的UIImage方法,resizableImageWithCapInsets:,可以将图片转换为以某一偏移值为偏移的可伸缩图像(偏移值内的图像将不被拉伸或压缩)。

    用法引述如下:

    resizableImageWithCapInsets:

    Creates and returns a new image object with the specified cap insets.
    - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets
    Parameters
    capInsets
    The values to use for the cap insets. 

    typedef struct {
    CGFloat top, left, bottom, right;
    } UIEdgeInsets; 分别表示上左下右四个方向的偏移量。于是把上面按钮的UIImage改为如下形式:

    UIImage *buttonImage = [[UIImage imageNamed:@”blueButton”]
    resizableImageWithCapInsets:UIEdgeInsetsMake(0, 16, 0, 16)];

    可以得到如下按钮:

    问题得到解决。

    但是值得注意的是该方法需要至少iOS5的运行环境,因此对于需要开发支持iOS5之前的App来说是不可行的。替代方案是stretchableImageWithLeftCapWidth:topCapHeight:,但是在iOS5中,这已经是被Deprecated的方法了,而且该方法只能以1px作为重复铺满拉伸区域,无法做到类似渐变等图片效果,是存在一定局限的。

    简单的说

    UIImage *backButton = [[UIImage imageNamed:@”blueButton”]
    resizableImageWithCapInsets:UIEdgeInsetsMake(12, 12, 12, 12)];

    让图片在UIEdgeInsetsMake(12, 12, 12, 12)这个范围内拉伸,距离图片top的12像素处,buttom的12像素处内拉伸,其他区域不拉伸。

  • 相关阅读:
    UI: 多窗口
    UI: 标题栏
    控件 UI: 字体的自动继承的特性, Style, ControlTemplate
    控件 UI: VisualState, VisualStateManager, 控件的默认 UI
    控件 UI: StateTrigger
    atoi、stoi、strtoi区别
    python下载IGS观测数据
    稳健估计
    间接平差程序实现
    android中的文件操作详解以及内部存储和外部存储(转载)
  • 原文地址:https://www.cnblogs.com/lihaibo-Leao/p/3285285.html
Copyright © 2011-2022 走看看