使用多个子视图使交叉点透明

时间:2011-12-27 07:15:05

标签: iphone objective-c ios transparent

请查看下图。我添加了“BLACK”颜色的scrollview并添加了“GRAY”颜色的子视图。现在我想让子视图透明,定义为“白色”颜色。

请参阅以下代码。让我知道如何使按钮透明与特定框架或让我知道你是否有任何替代方案。

self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 40.0, self.frame.size.width, 300.0)];
self.scrollView.contentSize = CGSizeMake(self.bounds.size.width,ViewHeight);
self.scrollView.autoresizingMask=UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.scrollView.delegate = self;
self.scrollView.backgroundColor =[UIColor blackColor];
[self.view addSubview:self.scrollView


UIButton *butApp = [UIButton buttonWithType:UIButtonTypeCustom];
[butApp setFrame:CGRectMake(x, y , w, h)];
[butApp setBackgroundColor:[UIColor greyColor]];
[self.scrollView addSubview:butApp];


UIButton* gapButton = [UIButton buttonWithType:UIButtonTypeCustom];
[gapButton setFrame:CGRectMake(x+3, y+10, w-6, 10)];
[gapButton setBackgroundColor:[UIColor whiteColor]];
[self.scrollView addSubview:gapButton];

而不是这个gapButton我需要灰色的透明部分,以便用户可以在该部分看到黑色。

enter image description here

2 个答案:

答案 0 :(得分:0)

试试这个,我在评论中提出了这个建议。其他答案需要子类化UIButton,你建议在你的情况下不理想。

UIButton *butApp = [UIButton buttonWithType:UIButtonTypeCustom];
[butApp setFrame:CGRectMake(x, y , w, h)];
//[butApp setBackgroundColor:[UIColor greyColor]]; //replace this...
[butApp setBackgroundImage:[UIImage imageNamed:@"greyWithHoleInCenter.png"]
                   forState:UIControlStateNormal]; //...with this
[self.scrollView addSubview:butApp];

我创建了一个粗略的.png文件来表示您可能正在寻找的backgroundImage类型。请注意,中心是清晰的,而不是白色。因此,它应该显示它背后的任何图像:

button with hole

答案 1 :(得分:0)

确定。有趣的问题。在我看来,你必须通过子类化UIView类来覆盖drawRect:+ drawInContext:方法。 您还需要将容器视图(灰色视图)+按钮bg设置为clearColor

-(void)drawRect:(CGRect)r
{
 // Let this method blank will cause drawLayer:InContext to be called
}

-(void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context
{
       // Fill the bg with gray 
    CGContextSetFillColorWithColor(context, [UIColor grayColor].CGColor);
    CGContextFillRect(context, self.bounds);

      // I clear the subview frames
    for (UIView * v in [self subviews]) // I do it for all subviews
    {
        CGContextSetBlendMode(context, kCGBlendModeClear);
        CGContextFillRect(context, v.frame);
    }
}

here is a screen shot

相关问题