iOS

UILabel文字渐变

UILabel文字渐变

920 发布: 2024/4/20 20:06 本文总阅读量
- (void)drawRect:(CGRect)rect {
    
    //NSLog(@"====>%f======%f====%@",rect.size.width,rect.size.height,self.text);
    
    CGSize textSize = [self.text sizeWithAttributes:@{NSFontAttributeName : self.font}];
    CGFloat start_x = (rect.size.width - textSize.width)/2;
    CGFloat start_y = (rect.size.height - textSize.height)/2;
    CGFloat end_x = start_x + textSize.width;
    CGFloat end_y = start_y + textSize.height;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 获取文字mask
    CGRect textRect = CGRectMake(start_x, start_y, textSize.width, textSize.height);
    [self.text drawInRect:textRect withAttributes:@{NSFontAttributeName : self.font}];
    CGImageRef textMask = CGBitmapContextCreateImage(context);
    
    // 清空画布
    CGContextClearRect(context, rect);
    
    // 设置蒙层
    CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextClipToMask(context, rect, textMask);
    
    // 绘制渐变
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    /*
    CGFloat locations[] = {0, 0.5, 1};
    CGFloat colors[] = {1.0,0.0,0.0,1.0,
                        0.0,1.0,0.0,1.0,
                        0.0,0.0,1.0,1.0};
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colors, locations, 3);
    */
    
    /**
     * 注意:这里固定了渐变色值
     * 颜色数组 FAACFF【250,172,255】  921AF1【146,26,241】
     * 可自行实现利用gradientColors将十六进制转为rgba填写到此处
     */
    CGFloat colors[] = {
        0.57,0.10,0.95,1.0,
        0.98,0.67,1.00,1.0
    };
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colors, NULL, 2);
    // 从上到下
    CGPoint startPoint = CGPointMake(end_x, start_y);
    CGPoint endPoint = CGPointMake(end_x, end_y);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation);
    
    // 释放
    CGColorSpaceRelease(colorSpace);
    CGGradientRelease(gradient);
    CGImageRelease(textMask);
}