|
| 1 | +// |
| 2 | +// FLXSmoothView.m |
| 3 | +// SmoothCorners |
| 4 | +// |
| 5 | +// Created by Felix Lapalme on 2019-03-24. |
| 6 | +// Copyright © 2019 Felix Lapalme. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +#import "FLXSmoothView.h" |
| 10 | + |
| 11 | +@interface FLXSmoothView() |
| 12 | + |
| 13 | +@property (nonatomic, assign) CGFloat flx_lastSetRadius; |
| 14 | +@property (nonatomic, strong) CAShapeLayer *flx_smoothMask; |
| 15 | + |
| 16 | +@end |
| 17 | + |
| 18 | +@implementation FLXSmoothView |
| 19 | + |
| 20 | +-(void)setFlx_smoothCorners:(BOOL)flx_smoothCorners { |
| 21 | + _flx_smoothCorners = flx_smoothCorners; |
| 22 | + |
| 23 | + [self flx_updateMaskIfNeeded]; |
| 24 | +} |
| 25 | + |
| 26 | +- (void)layoutSubviews { |
| 27 | + [super layoutSubviews]; |
| 28 | + |
| 29 | + if (self.flx_smoothCorners) { |
| 30 | + [self flx_updateMaskIfNeeded]; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +- (void)flx_updateMaskIfNeeded { |
| 35 | + if (self.flx_smoothCorners) { |
| 36 | + if (self.flx_smoothMask) { |
| 37 | + // If it already exists we only update it if it changed |
| 38 | + if (!CGRectEqualToRect(CGPathGetPathBoundingBox(self.flx_smoothMask.path), self.bounds) |
| 39 | + || self.flx_lastSetRadius != self.layer.cornerRadius) { |
| 40 | + [self flx_updateMaskShape]; |
| 41 | + } |
| 42 | + } else { |
| 43 | + UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds |
| 44 | + cornerRadius:self.layer.cornerRadius]; |
| 45 | + CAShapeLayer *mask = [CAShapeLayer layer]; |
| 46 | + mask.path = maskPath.CGPath; |
| 47 | + self.layer.mask = mask; |
| 48 | + self.flx_smoothMask = mask; |
| 49 | + self.flx_lastSetRadius = self.layer.cornerRadius; |
| 50 | + |
| 51 | + [self.layer addObserver:self |
| 52 | + forKeyPath:NSStringFromSelector(@selector(cornerRadius)) |
| 53 | + options:0 |
| 54 | + context:nil]; |
| 55 | + } |
| 56 | + } |
| 57 | + else if (self.flx_smoothMask) { |
| 58 | + self.layer.mask = nil; |
| 59 | + self.flx_smoothMask = nil; |
| 60 | + |
| 61 | + @try { |
| 62 | + [self.layer removeObserver:self forKeyPath:NSStringFromSelector(@selector(cornerRadius))]; |
| 63 | + } |
| 64 | + @catch (NSException * __unused exception) {} |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +- (void)flx_updateMaskShape { |
| 69 | + self.flx_smoothMask.path = [UIBezierPath bezierPathWithRoundedRect:self.bounds |
| 70 | + cornerRadius:self.layer.cornerRadius].CGPath; |
| 71 | + self.flx_lastSetRadius = self.layer.cornerRadius; |
| 72 | +} |
| 73 | + |
| 74 | +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context { |
| 75 | + if ([keyPath isEqualToString:NSStringFromSelector(@selector(cornerRadius))]) { |
| 76 | + [self flx_updateMaskIfNeeded]; |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +@end |
0 commit comments