简体   繁体   中英

Blur UILabel in Swift

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,

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM