简体   繁体   中英

make a portion of a UIView become transparent

I have a UIView w/c I returned as view in my viewForHeaderInSection. Now, I want to make a small transparent square on the lower right of the view so the cells will be seen through. How can I achieve something like this? Do I need to use this CGContextSetBlendMode? can anyone shed light on this.

Here is a UIView subclass solution. In order for this to work you must leave the superviews backgroundColor property as nil witch is the default value. If this UIView-subclass is in the storyboard then make sure you set the background color to "Clear color" in the attributes inspector.

- (void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    UIColor *blackBackgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
    CGContextSetFillColorWithColor(ctx, blackBackgroundColor.CGColor);
    CGContextFillRect(ctx, rect);
    CGRect transparentPart = CGRectMake(10, 10, 120, 80);
    CGContextClearRect(ctx, transparentPart);
}
CALayer *layer = [[CALayer alloc] init];
[layer setFrame:yourBoundsInView];

[[yourView layer] setMask:layer];

or override the drawRect method and add the below lines of code at the end

UIBezierPath *seeThrough = [UIBezierPath bezierPathWithRect:seeThroughRect];
[[UIColor colorWithWhite:1 alpha:0] set];
[seeThrough fillWithBlendMode:kCGBlendModeSourceIn alpha:1];

You need to apply mask for your View.

Tutorial: https://medium.com/@peteliev/layer-masking-for-beginners-c18a0a10743

The view are inserted as subviews inside of SwitchViewController.view. So, they will always appear above the SwitchViewControllers view. The other view is removed, Only one view will be appeared at 1 time

eg Here

[yellowViewController.view removeFromSuperview];
[self.view insertSubview:blueViewController.view atIndex:0];

view appears behind its subview by default, and

insertSubview:atIndex:

can't place it behind the view itself, as a view is not contained in the list of its own subviews.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM