Evghenii Todorov
Evghenii Todorov

Reputation: 677

UILabel colored in 2 colors vertically

Is it possible with iOS SDK to color text in UILabel in two colors vertically, like on the image - top half is gray and bottom half is white?

enter image description here

Thanks

Upvotes: 1

Views: 532

Answers (2)

Govind Prajapati
Govind Prajapati

Reputation: 957

Yes, you can with the help of the CoreGarphics:

Step one:

get the BezierPath of your text with below function ->

-(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;
}

Step two:

Now make a gradient layer and mask it with your text path with fill color = clear color so that gradient layer will be visible from your text.

Upvotes: 0

dip
dip

Reputation: 3598

You can try setting color with image to the label,

Add the following method

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!
}

and set color to your label like

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

Upvotes: 2

Related Questions