思路參考
舉例UIButtom思路:
1镇饮、 首先創(chuàng)建一個(gè)臨時(shí)的 UIView
2、 然后利用 CAGradientLayer 在 UIView 上面進(jìn)行漸變繪制
3术羔、將UIView 進(jìn)行截圖返回 UIImage
4杨箭、將返回的 UIImage 設(shè)置到 UIButton 的 setBackgroundImage
這樣就可以完成了一個(gè)UIButton 的漸變色 繪制寞焙,并且可以根據(jù)不用的顏色來設(shè)置Button UIControlStateNormal | UIControlStateHighlighted | UIControlStateDisabled 來進(jìn)行設(shè)置效果。
5、在已經(jīng)繪制好有漸變色的UIView 上面蓋多一個(gè)白色的 UIView 比 上面那個(gè)UIView 小一些像素 即可
下面直接貼代碼
/**
btnRect:按鈕的frame
borderWidth:按鈕的邊框?qū)挾? 默認(rèn)圓角為高度的1/2捣郊,修改圓角需要修改gradientLayer和whiteView的cornerRadius
*/
- (UIImage *)getImageWithFrame:(CGRect)btnRect withBorderWidth:(CGFloat)borderWidth{
CGFloat btnWidth = btnRect.size.width;
CGFloat btnHeight = btnRect.size.height;
//用來放置漸變色的view
UIView *crView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, btnWidth, btnHeight)];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:1 green:172/255.0 blue:64/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:254/255.0 green:119/255.0 blue:119/255.0 alpha:1].CGColor];
gradientLayer.locations = @[@0.3, @0.7];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame = CGRectMake(0, 0, crView.frame.size.width, crView.frame.size.height);
gradientLayer.cornerRadius = btnHeight*1.0/2;
[crView.layer addSublayer:gradientLayer];
//空白view
UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(borderWidth, borderWidth, btnWidth-borderWidth*2, btnHeight-borderWidth*2)];
whiteView.layer.cornerRadius = btnHeight*1.0/2;
whiteView.backgroundColor = [UIColor whiteColor];
[crView addSubview:whiteView];
//把配置好的view轉(zhuǎn)變成image
CGSize s = CGSizeMake(btnWidth, btnHeight);
// 下面方法辽狈,第一個(gè)參數(shù)表示區(qū)域大小。第二個(gè)參數(shù)表示是否是非透明的呛牲。如果需要顯示半透明效果刮萌,需要傳NO,否則傳YES娘扩。第三個(gè)參數(shù)就是屏幕密度了
UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
[crView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
使用方法:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 200, 200, 50);
[btn setTitle:@"+關(guān)注" forState:UIControlStateNormal];
[btn setBackgroundImage:[self getImageWithFrame:btn.frame withBorderWidth:0.5] forState:UIControlStateNormal];
[self.view addSubview:btn];
參考文檔還寫了漸變文字的方法着茸,我嘗試了下沒成功,改天再看