UIView中间透明

时间:2014-06-13 02:26:48

标签: ios objective-c uiview transparent

enter image description here

是否可以使用颜色创建这样的UIView填充,但中间是否透明?

我正在考虑在这里创建 5 UIView。只是想知道只使用一个UIView

就可以实现

3 个答案:

答案 0 :(得分:6)

Duncan C开始,我知道应该从哪里开始,然后我找到CALayer with transparent hole in it

UIBezierPath *overlayPath = [UIBezierPath bezierPathWithRect:self.view.bounds];
UIBezierPath *transparentPath = [UIBezierPath bezierPathWithRect:CGRectMake(60, 120, 200, 200)];
[overlayPath appendPath:transparentPath];
[overlayPath setUsesEvenOddFillRule:YES];

CAShapeLayer *fillLayer = [CAShapeLayer layer];
fillLayer.path = overlayPath.CGPath;
fillLayer.fillRule = kCAFillRuleEvenOdd;
fillLayer.fillColor = [UIColor colorWithRed:255/255.0 green:20/255.0 blue:147/255.0 alpha:1].CGColor;

[self.view.layer addSublayer:fillLayer];

使用2 UIBezierPath,然后填充我想要的颜色(我的问题是粉红色),然后添加为子图层

答案 1 :(得分:0)

是的,这是可能的。您可以将遮罩层附加到视图的图层,然后“打出”遮罩的中心部分。这实际上很容易。

答案 2 :(得分:0)

您创建一个视图作为UIView的子类并添加以下代码: 在YourView.h中

#import <UIKit/UIKit.h>

@interface YourView : UIView

@property (nonatomic, assign) CGRect rectForClearing;
@property (nonatomic, strong) UIColor *overallColor;

@end

在YourView.m中

#import "YourView.h"

@implementation NBAMiddleTransparentView

- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder // support init from nib
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [super drawRect:rect];
    CGContextRef ct = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(ct, self.overallColor.CGColor);
    CGContextFillRect(ct, self.bounds);
    CGContextClearRect(ct, self.rectForClearing);
}

@end

使用:

yourView.overallColor = [UIColor redColor];
yourView.rectForClearing = CGRectMake(20, 20, 20, 20);

希望这有帮助!