ikajava
ikajava

Reputation: 227

How to create CGPathRef from UILabel text?

I'm going to make an shadow path for UILabel, which outlines the text of it. Is the UILabel text somehow convertable to CGPath?

Upvotes: 0

Views: 233

Answers (1)

Rob
Rob

Reputation: 437562

I’d suggest that the easiest approach is set the shadow properties of the layer.

In Objective-C:

self.label.layer.shadowColor = UIColor.blackColor.CGColor;
self.label.layer.shadowRadius = 10;
self.label.layer.shadowOpacity = 1;
self.label.layer.shadowOffset = CGSizeZero;

In Swift:

label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowRadius = 10
label.layer.shadowOpacity = 1
label.layer.shadowOffset = .zero

Yielding:

enter image description here

You said:

But, in layers I have some additional content, where I don't want to add the shadow.

If you have subviews or sublayers that are interfering with the shadow, I’d suggest you move that content out of the label and into their own view hierarchy. It’s hard to be specific without knowing what sublayers/subviews you’ve added to your label.


You said:

... I need opacity of the shadow too and it's impossible without layers.

That’s not entirely true. You can use the NSAttributedString pattern and specify the alpha as part of the shadowColor.

E.g. in Objective-C:

NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowOffset = CGSizeZero;
shadow.shadowBlurRadius = 20;
shadow.shadowColor = [UIColor.blackColor colorWithAlphaComponent:1];

NSDictionary<NSAttributedStringKey, id> *attributes = @{ NSShadowAttributeName: shadow };

NSMutableAttributedString *string = [self.label.attributedText mutableCopy];
[string setAttributes:attributes range:NSMakeRange(0, string.length)];

self.label.attributedText = string;

Or in Swift:

let shadow = NSShadow()
shadow.shadowOffset = .zero
shadow.shadowBlurRadius = 20
shadow.shadowColor = UIColor.black.withAlphaComponent(1)

let attributes: [NSAttributedString.Key: Any] = [.shadow: shadow]

guard let string = label.attributedText?.mutableCopy() as? NSMutableAttributedString else { return }
string.setAttributes(attributes, range: NSRange(location: 0, length: string.length))
label.attributedText = string

Upvotes: 1

Related Questions