如何重绘UIView的形状并同时给它一个阴影?

时间:2016-03-30 09:26:54

标签: ios objective-c swift uiview

我的UIView + Shape.h文件

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface UIView (Shape)

- (void)setShape:(CGPathRef)shape;

@end

我的UIView + Shape.m文件

#import "UIView+Shape.h"

@implementation UIView (Shape)

- (void)setShape:(CGPathRef)shape
{
    if (shape == nil) {
        self.layer.mask = nil;
    }

    CAShapeLayer* maskLayer = [CAShapeLayer layer];
    maskLayer.path = shape;
//    self.layer.mask = maskLayer;
    self.layer.shadowOffset = CGSizeMake(0, 2);
    self.layer.shadowOpacity = 0.80;
}

@end

我的UIBezierPath + BasicShape.h文件

#import <UIKit/UIKit.h>

@interface UIBezierPath (BasicShape)

+ (UIBezierPath *)cutCorner:(CGRect)originalFrame length:(CGFloat)length;

@end

我的UIBezierPath + BasicShape.m文件

#import "UIBezierPath+BasicShape.h"

@implementation UIBezierPath (BasicShape)

+ (UIBezierPath *)cutCorner:(CGRect)originalFrame length:(CGFloat)length
    {
    CGRect rect = originalFrame;
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];

    [bezierPath moveToPoint:CGPointMake(0, 0)];
    [bezierPath addLineToPoint:CGPointMake(rect.size.width - length, 0)];
    [bezierPath addLineToPoint:CGPointMake(rect.size.width - length, 15)];
    [bezierPath addLineToPoint:CGPointMake(rect.size.width, 25)];
    [bezierPath addLineToPoint:CGPointMake(rect.size.width - length, 35)];
    [bezierPath addLineToPoint:CGPointMake(rect.size.width - length, rect.size.height)];
    [bezierPath addLineToPoint:CGPointMake(0, rect.size.height)];
    [bezierPath closePath];
    return bezierPath;
}

@end

通过导入这两个类并使用像

这样的句子
[filterList setShape:[UIBezierPath cutCorner:filterList.bounds length:10].CGPath];

filterlist是我的UIView。

结果为annotate 'self.layer.mask = maskLayer;'

annotate another two sentences

但我只想为这个观点获得这两种效果。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

多么愚蠢的问题! 我只是在我的filterListView后面创建另一个shadowView,然后得到我想要的效果!

答案 1 :(得分:0)

还有另一种选择,添加一个已设置阴影的子图层。

CAShapeLayer* maskLayer = [CAShapeLayer layer];
maskLayer.path = shape;
maskLayer.shadowOffset = CGSizeMake(0, 2);
maskLayer.shadowOpacity = 0.80;
maskLayer.fillColor = [UIColor lightGrayColor].CGColor;
[self.layer addSublayer:maskLayer];