设置CGContext透明背景

Jim*_*m B 50 iphone graphics background transparent cgcontext

我仍然在努力用CGContext绘制一条线.我实际上去绘制线条,但现在我需要将Rect的背景透明,以便现有的背景显示出来.这是我的测试代码:

(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);
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Dav*_*rek 72

UIGraphicsGetCurrentContext()通话结束后CGContextClearRect(context,rect)

编辑:好吧,明白了.

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

- (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);
}
Run Code Online (Sandbox Code Playgroud)

我的测试使用它作为一个非常基本的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];
}
Run Code Online (Sandbox Code Playgroud)

  • 背景是黑色的,必须是iphone背景.我实际上是想在UIView之上画画. (7认同)

ZGl*_*XNt 41

简单的方法:

- (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
}
Run Code Online (Sandbox Code Playgroud)

  • 我在表视图单元格中使用它作为附件指示器.self.opaque = NO在接受的答案中[self setBackgroundColor:[UIColor clearColor]]不起作用. (4认同)

onm*_*133 7

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

UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) 
Run Code Online (Sandbox Code Playgroud)

不透明

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