如何在iOS中构建带阴影的透明视图?

时间:2014-04-09 03:28:11

标签: ios objective-c uiview drawrect

我想构建一个完全透明的视图,backgroundColor可能是clearColor。在这个视图中我想放一个小图像。而在这个透明视图的四个方面,我想看到阴影的效果。阴影必须完全在视野之外。我知道我必须覆盖UIView中的drawRect方法,但不知道如何做到这一点。

2 个答案:

答案 0 :(得分:1)

试试这个......

    UIView *shadowView = [[UIView alloc] initWithFrame:CGRectMake(50.0, 100.0, 100.0, 100.0)];
    shadowView.layer.cornerRadius = 15.0;
    CALayer *layer = shadowView.layer;
    layer.shadowOpacity = 1.0;
    layer.shadowColor = [[UIColor blackColor] CGColor];
    layer.shadowOffset = CGSizeMake(0,0);
    layer.shadowRadius = 15;
    [self.view addSubview:shadowView];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
    [imageView setImage:[UIImage imageNamed:@"icon.png"]];
    [shadowView addSubview:imageView];

答案 1 :(得分:-1)

做这样的事情有什么问题?

#import <QuartzCore/QuartzCore.h> // at the top of the file

UIView *transparentView = [[UIView alloc] initWithFrame:CGRectMake(50,50,200,200)];
transparentView.backgroundColor = [UIColor greenColor];
transparentView.alpha = 0.5f;
transparentView.clipsToBounds = NO;
transparentView.layer.shadowColor = [UIColor blackColor].CGColor;
transparentView.layer.shadowOpacity = 1;
transparentView.layer.shadowRadius = 1;

UIImageView *imageView = [[]UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
imageView.image = [UIImage imageNamed:@"IMAGE NAME"];
[transparentView addSubview:imageView]; 

正如您所看到的,根据您的描述,不需要drawRect:,除非出于某种原因您想手动绘制阴影,但没有理由。