Some time ago I wrote a text gradient of the demo, and recently on the Internet to see a new way to set the text gradient, the two methods to share it, I think there should be a good variety of methods, after seeing and then add.
:
In fact, the two methods to achieve the principle and ideas are similar, but the use of classes and methods are not the same.
(i) _ Custom label, implement DrawRect method, in this method to paint the gradient color
Ideas: 1 _ Put the text of the label to the context (the role of the text is mainly set layer mask)
Cgcontextref context = uigraphicsgetcurrentcontext();
[self textcolor set];
[self text drawwithrect:rect Options:nsstringdrawinguseslinefragmentorigin attributes:@{nsfontattributename self. Font} context:null
2) _ Set Mask: cgcontextcliptomask(context, rect, alphamask) and clear text
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); clear previously drawn text
Cgcontextcliptomask(context, rect, alphamask);
3) _ Flip the coordinates, paint the gradient
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);
// free memory
cgcolorspacerelease(colorspace);
cggradientrelease(gradient);
cfrelease(alphamask);
(b) _ No custom label is required, use cagradientlayer Setting a gradient layer
Idea: 1 _ New label, add label to view (this label layer is only set mask, not to display)
2) _ Create a cagradientlayer, set its gradient, add it to the layer of the label's Superview, and overwrite it on the label
3) _ Set gradientlayer mask to label the layer to reset the label frame
specific detailed code has been written into the demo upload to GitHub (Click to view)
Reference: text Gradient Effect: Mask property in a layer
Two ways to achieve the gradual color change of iOS text