專案中需要實現的效果:
實現方法:自定義cfgradientlabel繼承於uilabel,實現 drawrect: 方法,在該方法裡面畫漸變色。
在 cfgradientlabel.h 裡
在cfgradientlabel.m 裡#import @inte***ce cfgradientlabel : uilabel
@property (nonatomic,copy) nsarray *colors;
@end
建立漸變色label:#import "cfgradientlabel.h"
@implementation cfgradientlabel
- (void)drawrect:(cgrect)rect
]; cgrect textrect = (cgrect);
// 畫文字(不做顯示用,主要作用是設定layer的mask)
cgcontextref context = uigraphicsgetcurrentcontext();
[self.textcolor set];
[self.text drawwithrect:rect options:nsstringdrawinguseslinefragmentorigin attributes:@ context:null];
// 座標
cgcontexttranslatectm(context, 0.0f, rect.size.height- (rect.size.height - textsize.height)*0.5);
cgcontextscalectm(context, 1.0f, -1.0f);
cgimageref alphamask = null;
alphamask = cgbitmapcontextcreateimage(context);
cgcontextclearrect(context, rect);// 清除之前畫的文字
// 設定mask
cgcontextcliptomask(context, rect, alphamask);
// 畫漸變色
cgcolorspaceref colorspace = cgcolorspacecreatedevicergb();
cggradientref gradient = cggradientcreatewithcolors(colorspace, (__bridge cfarrayref)self.colors, null);
cgpoint startpoint = cgpointmake(textrect.origin.x,
textrect.origin.y);
cgpoint endpoint = cgpointmake(textrect.origin.x + textrect.size.width,
textrect.origin.y + textrect.size.height);
cgcontextdrawlineargradient(context, gradient, startpoint, endpoint, kcggradientdrawsbeforestartlocation | kcggradientdrawsafterendlocation);
// 釋放記憶體
cgcolorspacerelease(colorspace);
cggradientrelease(gradient);
cfrelease(alphamask);
}@end
cfgradientlabel *gradientlbl = [[cfgradientlabel alloc] init];
[self.view addsubview:gradientlbl];
[gradientlbl mas_makeconstraints:^(masconstraintmaker *make) ];
gradientlbl.text = @"(確定後無法更改)";
gradientlbl.font = font(13);
gradientlbl.colors = @[(id)rgb(254, 42, 61).cgcolor,(id)rgb(255, 198, 21).cgcolor];
gradientlbl.layer.maskstobounds = yes;
iOS文字漸變色效果的實現方法
照例先上文字漸變的效果圖 實現思路如下 一 建立乙個顏色漸變層,漸變圖層跟文字控制項一樣大。二 用文字圖層裁剪漸變層,只保留文字部分,就會讓漸變層只保留有文字的部分,相當於間接讓漸變層顯示文字,我們看到的其實是被裁剪過後,漸變層的部分內容。注意 如果用文字圖層裁剪漸變層,文字圖層就不在擁有顯示功能,...
iOS 漸變色實現,漸變色圓環,圓環進度條
cagradientlayer圖層可以通過設定mask來給檢視新增漸變效果 cagradientlayer主要需要設定一下幾個引數 colors 傳入需要漸變的顏色 例如 self.gradientlayer.colors bridge id uicolor orangecolor cgcolor,...
iOS開發之漸變色的實現
向凡神致敬 brief 建立乙個cagradientlayer物件用於放置需要漸變的顏色 cagradientlayer gradient cagradientlayer layer brief 獲取當前要設定顏色漸變的空間的bounds gradient.frame self view bound...