首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >设置CGContext透明背景

设置CGContext透明背景
EN

Stack Overflow用户
提问于 2010-01-24 09:38:55
回答 8查看 46.4K关注 0票数 54

我仍然在努力与CGContext划清界限。我实际上已经去画线,但现在我需要矩形的背景是透明的,以便现有的背景显示通过。下面是我的测试代码:

代码语言:javascript
运行
复制
(void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
    CGContextSetAlpha(context,0.0);
    CGContextFillRect(context, rect);

    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(context, 5.0);
    CGContextMoveToPoint(context, 100.0,0.0);
    CGContextAddLineToPoint(context,100.0, 100.0);
    CGContextStrokePath(context);
}

有什么想法吗?

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2010-01-24 09:45:52

UIGraphicsGetCurrentContext()之后调用CGContextClearRect(context,rect)

编辑:好的,明白了。

包含行的自定义视图应具有以下内容:

代码语言:javascript
运行
复制
- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(context, 5.0);
    CGContextMoveToPoint(context, 100.0,0.0);
    CGContextAddLineToPoint(context,100.0, 100.0);
    CGContextStrokePath(context);
}

我的测试使用了这个非常基本的UIViewController:

代码语言:javascript
运行
复制
- (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView *v = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [v setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:v];
    TopView *t = [[TopView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:t];
    [v release];
    [t release];
}
票数 74
EN

Stack Overflow用户

发布于 2012-01-28 22:17:48

简单的方法:

代码语言:javascript
运行
复制
- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {       
        self.opaque = NO;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    //your code
}
票数 43
EN

Stack Overflow用户

发布于 2017-06-22 18:37:26

使用opaque == false初始化上下文,Swift 3

代码语言:javascript
运行
复制
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) 

不透明

指示位图是否不透明的布尔标志。如果知道位图是完全不透明的,请指定true以忽略alpha通道并优化位图的存储。指定false意味着位图必须包含一个alpha通道来处理任何部分透明的像素。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2125543

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档