clipsToBounds=YES与shadow如何共存

有时候我们需要用view.clipsToBounds=YES来裁剪图片防止图片显示的范围超出了UIImageView的大小,如果这个时候还需要给这个UIImageViewshadow的话,可能会遇到一些问题。

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    imageView.image = [UIImage imageNamed:@"1.jpg"];
    imageView.contentMode=UIViewContentModeScaleAspectFill;
    imageView.layer.shadowColor = [UIColor blackColor].CGColor;
    imageView.layer.shadowOffset = CGSizeMake(10, 10);
    imageView.layer.shadowRadius = 10;
    imageView.layer.shadowOpacity = 1.0;
    imageView.clipsToBounds = YES;
    [self.view addSubview:imageView];

这个时候显示的就是
QQ20160721-0@2x
UIImageView并没有出现shadow,这是因为当我们设置clipsToBoundsYES时,这个视图和其子视图的内容超出其bounds的部分都会被裁剪掉。而shadow是在视图的bounds之外的。因此这样设置是看不到shadow的。
换一种方式

    UIView *shadowView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
    shadowView.layer.shadowOffset = CGSizeMake(5, 5);
    shadowView.layer.shadowRadius = 5;
    shadowView.layer.shadowOpacity = 1.0;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    imageView.image = [UIImage imageNamed:@"1.jpg"];
    imageView.contentMode=UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [shadowView addSubview:imageView];
    [self.view addSubview:shadowView];

QQ20160721-1@2x

我们创建一个专门用来产生shadow的视图,将UIImageView加到这个视图上,由于imageViewshadowView的子视图,在imageView上设置clipsToBoundsYES并不会影响到shadowView
这种办法并不优雅,然而并不知道还有什么解决的办法。