设置 CGContext 透明背景 [英] Setting A CGContext Transparent Background

查看:28
本文介绍了设置 CGContext 透明背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在努力用 CGContext 画一条线.我实际上已经去画线了,但现在我需要 Rect 的背景是透明的,这样现有的背景就会显示出来.这是我的测试代码:

I am still struggling with drawing a line with CGContext. I have actually go to line to draw, but now I need the background of the Rect to be transparent so the existing background shows thru. Here's my test code:

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

有什么想法吗?

推荐答案

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

好的,知道了.

带有该行的自定义视图应具有以下内容:

Your custom view with the line should have the following:

- (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:

My test used this as a very basic UIViewController:

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

这篇关于设置 CGContext 透明背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆