2

How can I blur the text of UILabel?

UIBlurEffectView is not blurring the text but whole background.

Can you please let me know how can I achieve this?

Thank you,

nirav
  • 573
  • 5
  • 20

2 Answers2

0

As it was an interesting question, I looked up in UILabel documentation. There doesn't seem to be a method responsible for text drawing only, which could be overriden.

So my way of solving your problem would be this:

  1. Subclass a UIView with separate drawing methods for background and text.
  2. In the text drawing method, draw the text to an off-screen image.
  3. Then apply blur filter (Core Image framework) to that image.
  4. Draw the blurred image over the background (possibly your subclass may have 2 UIViews: one for the back and another for the text).

The obvious drawback of all this is that this custom subclass would miss all the features of attributed text and multiple-line division of the UILabel.

rommex
  • 763
  • 1
  • 8
  • 21
-1

You can achieve blurring just the text, without background, by using CATextLayer instead of UILabel. CALayer has a contentsScale property, and if you set it to value lower than screen's scale, you will achieve blur effect

let view = UIView()
let textLayer = CATextLayer()
textLayer.string = "yourText"
textLayer.contentsScale = 0.5 // lower number means more blurry text
view.layer.addSublayer(textLayer)

contentsScale defaults to 1.0, but for clear rendering of text it must be assigned the value of UIScreen.main.scale, which is 2.0 for most iPhones, with iPhone X being notable example with the value of 3.0. The lower the value, the more text will be blurred.

mag_zbc
  • 6,801
  • 14
  • 40
  • 62