如何在iOS中使用外部影子建立透明视图?

问题描述:

我想构建一个完全透明的视图,backgroundColor可能是clearColor。在这个视图里面我想放一个小图像。在这个透明观点的四面,我想看看影子的效果。阴影必须完全在视野外。我知道我必须重写UIView中的drawRect方法,但不知道如何执行此操作。如何在iOS中使用外部影子建立透明视图?

+0

你能请张贴图片或评估更多。 –

+0

为什么透明视图会有阴影;) – jrturton

+0

我只想要一个内部具有透明矩形的区域,并且在透明矩形的四边外部,我们可以看到一些效果,如阴影。 –

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

#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:,除非出于某种原因,你想手工绘制阴影,但没有一个理由。

+0

感谢您的建议,但问题是我希望视图完全透明,所以我需要将backgroundColor设置为clearcolor,但如果我这样做,阴影效果将消失。 –

+0

你应该用这个细节修改你的问题。 – Dima

+0

我已经做到了。那么你有另一种解决方案吗? –

试试这个....

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]; 
+0

实际上,阴影视图在其框架之外没有阴影效果。如果我使用clearColor背景设置阴影视图,imageview的阴影不是我想要的。 –