I want to achieve the effect from the picture bellow - a UILabel
that shows progress X as a gradient from bottom to X% of height of the label. The remaining (100 - X)% of the label will have a different color.
The only thing that comes into my mind right now is to create two UIViews
one with gray background and one with the color of the gradient. Put the gradient view above the gray view and set it’s height to match the current progress. Then simply use the label as a mask for those two views. For better illustration I attached a picture describing my suggested solution. Though I’m not happy with it because it is not very elegant.
Is it possible to achieve this in a different and more elegant way? Ideally just by subclassing UILabel
.
You can subclass
UILabel
and draw what you want indraw(_ rect: CGRect)
function. Or if you want to do it fast you can subclass too and add gradient subview. Don't forget to resize it inlayoutSubviews()
function.You could do this with layers and masks, but it will actually be easier to just set the text color with a UIColor from pattern image. This code works, though it might be better to subclass UILabel and give the class a method to apply and or update the image. I say this is easier, because I find dealing with text layers a bit of a pain to get the sizing perfect, where as labels can alter their font size with adjustsFontSizeToFitWidth.
You can use Core Animation with CATextLayer and CAGradientLayer.