在中间透明的UIView

5

这里输入图片描述

是否可能创建这样的一个UIView,它可以填充颜色,但中间是透明的?

我想在这里创建5UIView。只是在想是否可以仅使用一个UIView来完成。


CAShapeLayer - Mick MacCallum
请查看我的解决方案:https://dev59.com/M2zXa4cB1Zd3GeqPXMP-#32941652 - James Laurenstin
3个回答

7

我从Duncan C那里了解到应该从哪里开始,然后我找到了具有透明孔的CALayer

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

利用两个UIBezierPath,然后填充我想要的颜色(在我的问题中是粉色),最后添加为子层。

如果有人知道如何在触摸开始和触摸移动方法中透明化UI视图,请帮帮我。 - Milan patel
@milanpatel,不要在别人的帖子评论中发布新问题。请创建您自己的问题。 - Duncan C

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);

希望这能帮到你!


-1

是的,这是可能的。您可以将一个遮罩层附加到视图的层上,并“挖空”遮罩的中心部分。这实际上非常容易。


2
这个注释需要更详细地说明如何添加一个掩码并将其“打洞”。 - erparker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接