下面是我的两种实现:
1.直接图片展示,注意图片的变形问题;
2.用CAGradientLayer渐变颜色实现;
代码如下:
// // ViewController.m // ImageStrenchDemo // // Created by 思 彭 on 17/3/14. // Copyright © 2017年 思 彭. All rights reserved. // #import "ViewController.h" // rgb颜色转换(16进制->10进制) #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIImageView *headImgViewBg = [[UIImageView alloc] initWithFrame:self.view.bounds]; [headImgViewBg setImage:[UIImage imageNamed:@"bj"]]; [self.view addSubview:headImgViewBg]; [self setupUI]; [self setupImage]; } // 图片实现渐变 - (void)setupImage { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(100, 300, 300, 40); UIImage *image1 = [UIImage imageNamed:@"2"]; UIImage *resizeImage = [image1 resizableImageWithCapInsets:UIEdgeInsetsMake(image1.size.height*0.5, image1.size.width*0.3, image1.size.height*0.5, image1.size.width*0.5)resizingMode:UIImageResizingModeStretch]; [button setBackgroundImage:resizeImage forState:UIControlStateNormal ]; [button setTitle:@"dcevbvhvjrvrjvn" forState:UIControlStateNormal]; [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [self.view addSubview:button]; } // 颜色值实现渐变 - (void)setupUI { UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(30, 100, 300, 40)]; UIImageView *headImgViewBg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 40)]; bgView.layer.masksToBounds = YES; bgView.layer.cornerRadius = 20; [bgView addSubview:headImgViewBg]; [self.view addSubview:bgView]; CAGradientLayer *gradient = [CAGradientLayer layer]; gradient.frame = headImgViewBg.frame; gradient.colors = [NSArray arrayWithObjects:(id)UIColorFromRGB(0x752ccd).CGColor, (id)UIColorFromRGB(0xcd1f87).CGColor,nil]; gradient.startPoint = CGPointMake(0, 0.5); gradient.endPoint = CGPointMake(1, 0.5); [headImgViewBg.layer insertSublayer:gradient atIndex:0]; } @end