標籤:
前段時間我寫過一個文字漸層色的demo, 最近又在網上看到一個新的設定文字漸層色的方法, 就把這兩種方法分享出來吧, 我認為應該還有好多種方法, 以後看到後再補充.
:
其實這兩種方法實現原理及思路是差不多的, 只是使用的類和方法不一樣.
(一)_ 自訂label, 實現 drawRect 方法, 在該方法裡面畫漸層色
思路: 1)_ 把label的文字畫到context上去(畫文字的作用主要是設定 layer 的mask)
CGContextRef context = UIGraphicsGetCurrentContext();
[self.textColor set];
[self.text drawWithRect:rect options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.font} context:NULL];
2)_ 設定mask : CGContextClipToMask(context, rect, alphaMask); 並清除文字
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);// 清除之前畫的文字
CGContextClipToMask(context, rect, alphaMask);
3)_ 翻轉座標, 畫漸層色
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);
(二)_ 不需要自訂label, 利用 CAGradientLayer 設定漸層圖層
思路: 1)_ 建立label, 把label添加到view上(這個label圖層作用也只是設定mask, 不用來顯示)
2)_ 建立 CAGradientLayer, 設定其漸層色, 將其添加到 label 的superView的layer上, 並覆蓋在label上
3)_ 設定 gradientLayer的mask為 label的layer 重新設定label的frame
具體詳細代碼已經寫成demo 上傳到github(點擊查看)
參考: 文字漸層效果:圖層中的mask屬性
ios 文字漸層色實現的兩種方法