Gradient text in a UITextField

1k Views Asked by At

I'm using a CAGradientLayer to make a gradient background for a text field. It looks like this

enter image description here

Instead of the background I want to have the gradient on the text. How can I make gradient text in a UITextField?

The code I used to make the gradient in the image

pinkDarkOp = [UIColor colorWithRed:0.9f green:0.53f blue:0.69f alpha:1.0];
pinkLightOp = [UIColor colorWithRed:0.79f green:0.45f blue:0.57f alpha:1.0];

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = [[myTextField layer] bounds];
gradient.cornerRadius = 7;
gradient.colors = [NSArray arrayWithObjects:
                      (id)pinkDarkOp.CGColor,
                      (id)pinkLightOp.CGColor,
                      nil];
[[myTextField layer]addSublayer:gradient]; 
2

There are 2 best solutions below

3
On BEST ANSWER

You can solve this by creating two layers: First you create a layer which you fill with the gradient. Then you create another layer containing the text. Finally you use the second layer as a mask for masking the first layer. This is achieved by assigning the second layer to the mask property of the first layer.

If I look more specifically on your code example, I think that everything before the last line should be OK. But then you should replace the last line with something like this:

gradient.mask = myTextField.layer;

Perhaps you need to do some adjustments to myTextField as well (hard to say since its definition is not part of the listed code). It's important to understand that the text in the mask must be opaque but the rest of that layer must be fully transparent. Read about the "mask" property in the CALayer class reference: https://developer.apple.com/library/ios/DOCUMENTATION/GraphicsImaging/Reference/CALayer_class/Introduction/Introduction.html#//apple_ref/occ/instp/CALayer/mask

Dislaimer: I have not had time to test the code. I leave that to you. But the general idea of masking one layer with another should be possible to use, so I am convinced that you can sort out the details by yourself.

0
On

i made somme changes in my codes

pinkDarkOp = [UIColor colorWithRed:0.9f green:0.53f blue:0.69f alpha:1.0];
           pinkLightOp = [UIColor colorWithRed:0.79f green:0.45f blue:0.57f alpha:1.0];
        gradient.frame = [[myTextField layer] bounds];
        gradient.cornerRadius = 7;
       gradient.colors = [NSArray arrayWithObjects:(id)pinkDarkOp.CGColor,
                                             (id)[[UIColor clearColor] CGColor], nil]; 
           gradient.mask=myTextField.layer;

the text is invisible now enter image description here