UILabel垂直着色为2种颜色

时间:2017-04-18 09:25:37

标签: ios swift uilabel

iOS SDK是否可以在UILabel中以垂直两种颜色对文本进行着色,就像在图像上一样 - 上半部分是灰色,下半部分是白色?

enter image description here

由于

2 个答案:

答案 0 :(得分:2)

您可以尝试将图像颜色设置为标签

添加以下方法

func getGradientImage(_ bounds:CGRect) -> UIImage {

    let gradientLayer = CAGradientLayer()

    gradientLayer.colors = [
        UIColor(red: 0.596, green: 0.839, blue: 0.929, alpha: 1.00).cgColor,
        UIColor(red: 0.169, green: 0.302, blue: 0.408, alpha: 1.00).cgColor
    ]

    gradientLayer.startPoint = CGPoint.zero
    gradientLayer.endPoint = CGPoint(x: 1, y: 1) // changing start and end point value you can set vertical or horizontal
    gradientLayer.locations = [0.5,1]
    gradientLayer.bounds = bounds
    UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size, true, 0.0)

    let context = UIGraphicsGetCurrentContext()
    gradientLayer.render(in: context!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

并为您的标签设置颜色,如

yourLabel.textColor = UIColor(patternImage: getGradientImage(yourLabel.bounds))

答案 1 :(得分:0)

是的,你可以借助CoreGarphics:

第一步:

使用以下函数获取文本的BezierPath - >

-(UIBezierPath*)getPathOfStr{
 UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:64];
    CGFontRef fontref = CGFontCreateWithFontName((__bridge CFStringRef)font.fontName);
    NSString *unichars = @"I";
    CFStringRef yourFriendlyCFString = (__bridge CFStringRef)unichars;
    CGGlyph glyphs = CGFontGetGlyphWithGlyphName(fontref, yourFriendlyCFString);
    CTFontRef fontCT = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
    CGPathRef cgpath = CTFontCreatePathForGlyph(fontCT, glyphs, nil);
    UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:cgpath];
    NSLog(@"Complete path For p is %@", path);
    CGPathApply(cgpath, (__bridge void * _Nullable)(bezierPoints), MyCGPathApplierFunc);
    NSLog(@"Points on path %@", bezierPoints);

return path;
}

第二步:

现在制作一个渐变图层并使用填充颜色=清晰颜色的文本路径对其进行遮罩,以便从文本中看到渐变图层。