【问题标题】:Transparent background UIView drawRect circle透明背景 UIView drawRect 圆圈
【发布时间】:2014-07-02 05:15:26
【问题描述】:

我正在使用此代码绘制一个带有白色笔划和属性指定颜色的圆圈:

- (void)drawRect:(CGRect)rect {

    CGContextRef contextRef = UIGraphicsGetCurrentContext();

    CGContextClearRect(contextRef, rect);

    // Set the border width
    CGContextSetLineWidth(contextRef, 1.5);

    // Set the circle fill color to GREEN
    CGFloat red, green, blue, alpha;
    BOOL didConvert = [_routeColor getRed:&red green:&green blue:&blue alpha:&alpha];

    CGContextSetRGBFillColor(contextRef, red, green, blue, 1.0);

    // Set the cicle border color to BLUE
    CGContextSetRGBStrokeColor(contextRef, 255.0, 255.0, 255.0, 1.0);

    // Fill the circle with the fill color
    CGContextFillEllipseInRect(contextRef, rect);

    // Draw the circle border
    CGContextStrokeEllipseInRect(contextRef, rect);
}

我得到的图像是这样的:

如何去除黑色?

【问题讨论】:

  • 建议 - 摆脱对 CGContextSetRGBFillColorCGContextSetRGBStrokeColor 的调用。相反,请执行以下操作:[_routeColor setFill]; [[UIColor whiteColor] setStroke];。仅供参考 - 颜色值需要在 0.0 - 1.0 范围内,因此所有 255.0 值都应该是 1.0。

标签: ios objective-c uiview


【解决方案1】:

将视图的backgroundColor 设置为[UIColor clearColor]

请注意,设置背景颜色只需要在创建视图时进行一次。

【讨论】:

  • 要添加到这个答案 - 在自定义视图的 init 方法中设置背景颜色,而不是在 drawRect: 中。
  • 谢谢@rmaddy,我已经在答案中添加了注释。
【解决方案2】:

我需要这个。当我设置这个时,工作。

self.opaque = NO;

【讨论】:

    【解决方案3】:

    这在 Swift 3 上对我有用:

    self.isOpaque = false
    self.backgroundColor = UIColor.clear
    

    【讨论】:

    • 正如@ndnguyen 所说,您需要在 init 方法中设置这些属性
    • 您也可以将它们设置在故事板中。
    【解决方案4】:

    你需要在init中设置背景颜色为clearColor。

    这是一个例子

    -(id)initWithCoder:(NSCoder*)aDecoder
    {
        self = [super initWithCoder:aDecoder];
    
        if(self)
        {
            self.backgroundColor = [UIColor clearColor];
        }
    
        return self;
    }
    
    - (void)drawRect:(CGRect)rect {
    
        CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
        CGContextClearRect(contextRef, rect);
    
        // Set the border width
        CGContextSetLineWidth(contextRef, 1.5);
    
        // Set the circle fill color to GREEN
        CGFloat red, green, blue, alpha;
        BOOL didConvert = [_routeColor getRed:&red green:&green blue:&blue alpha:&alpha];
    
        CGContextSetRGBFillColor(contextRef, red, green, blue, 1.0);
    
        // Set the cicle border color to BLUE
        CGContextSetRGBStrokeColor(contextRef, 255.0, 255.0, 255.0, 1.0);
    
        // Fill the circle with the fill color
        CGContextFillEllipseInRect(contextRef, rect);
    
        // Draw the circle border
        CGContextStrokeEllipseInRect(contextRef, rect);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2013-06-28
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      相关资源
      最近更新 更多