简体   繁体   English

如何使用cornerradius删除CALayer周围的丑陋边框?

[英]How do I remove the ugly border around CALayer with cornerradius?

I'm drawing a simple line chart using Core Graphics. 我正在使用Core Graphics绘制一个简单的折线图。 I've created a custom class LineChart which inherits from UIControl . 我创建了一个继承自UIControl的自定义类LineChart On top of this chart I'd like to add a small filled circle that will be animated (change border color) on touch. 在此图表的顶部,我想添加一个小的填充圆圈,它将在触摸时进行动画处理(更改边框颜色)。

Here is the code for my circles at each (x,y) point. 这是我的圈子在每个(x,y)点的代码。

var layer = CALayer()
layer.borderColor = UIColor.whiteColor().CGColor
layer.backgroundColor = UIColor.blackColor().CGColor
layer.cornerRadius = 8
layer.borderWidth = 4
layer.frame = CGRect(x: xValue, y: yValue, width: 16, height: 16)
self.layer.addSublayer(layer)

I'd like to have a black center with a white border. 我想要一个带有白色边框的黑色中心。 The problem is that I have a tiny ugly black border around my outer white border. 问题是我的白色外边缘周围有一个丑陋的黑色边框。

CALayer周围的小丑陋边框

How can I get rid of this border? 我该怎样摆脱这个边界? I've played with antialiasing settings or added some Core Graphics with a small 1px white border on top but both didn't work out. 我玩过抗锯齿设置或者在顶部添加了一些带有1px白色边框的核心图形,但两者都没有用完。 The black background always shined through and created this outer border. 黑色背景总是闪闪发光,并创造了这个外边框。 I've seen CALayer Border strange issue but cannot believe that I really have to add two layers at each data point. 我见过CALayer Border奇怪的问题,但不能相信我真的要在每个数据点添加两层。

One way to work around the problem is to create a custom subclass of CALayer and override the drawInContext method to draw the bordered circle. 解决此问题的一种方法是创建CALayer的自定义子类并覆盖drawInContext方法以绘制带边框的圆。 Here's the class implementation 这是类实现

@implementation DotLayer

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super init];
    if ( self )
    {
        self.frame = frame;
        self.backgroundColor = [UIColor clearColor].CGColor;
        self.borderColor = [UIColor whiteColor].CGColor;
        [self setNeedsDisplay];
    }
    return( self );
}

- (void)setBorderColor:(CGColorRef)borderColor
{
    [super setBorderColor:borderColor];
    [self setNeedsDisplay];
}

- (void)drawInContext:(CGContextRef)context
{
    CGRect rect = self.bounds;
    CGContextSetFillColorWithColor( context, self.borderColor );
    CGContextFillEllipseInRect( context, rect );

    rect = CGRectInset( self.bounds, 4, 4 );
    CGContextSetFillColorWithColor( context, [UIColor blackColor].CGColor );
    CGContextFillEllipseInRect( context, rect );
}

@end

Here's the code to add a dot 这是添加点的代码

    DotLayer *layer = [[DotLayer alloc] initWithFrame:CGRectMake( xValue, yValue, 16, 16 )];
    [self.layer addSublayer:layer];

And here's the code to change the border color of a dot 这是改变点的边框颜色的代码

    layer.borderColor = [UIColor greenColor].CGColor;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM