为什么我的线条越来越厚?

时间:2010-04-21 16:33:06

标签: iphone core-graphics quartz-2d

我尝试绘制一些不同颜色的线条。

此代码尝试使用1px细线绘制两个矩形。但是,第二个矩形以2px宽度线绘制,而第一个矩形以1px宽度绘制。

- (void)addLineFrom:(CGPoint)p1 to:(CGPoint)p2 context:(CGContextRef)context {  
    // set the current point
    CGContextMoveToPoint(context, p1.x, p1.y);

    // add a line from the current point to the wanted point
    CGContextAddLineToPoint(context, p2.x, p2.y);
}


- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGPoint from, to;



    // ----- draw outer black frame (left, bottom, right) -----
    CGContextBeginPath(context);

    // set the color
    CGFloat lineColor[4] = {26.0f * colorFactor, 26.0f * colorFactor, 26.0f * colorFactor, 1.0f};
    CGContextSetStrokeColor(context, lineColor);

    // left
    from = CGPointZero;
    to = CGPointMake(0.0f, rect.size.height);
    [self addLineFrom:from to:to context:context];

    // bottom
    from = to;
    to = CGPointMake(rect.size.width, rect.size.height);
    [self addLineFrom:from to:to context:context];

    // right
    from = to;
    to = CGPointMake(rect.size.width, 0.0f);
    [self addLineFrom:from to:to context:context];

    CGContextStrokePath(context);
    CGContextClosePath(context);



    // ----- draw the middle light gray frame (left, bottom, right) -----

    CGContextSetLineWidth(context, 1.0f);
    CGContextBeginPath(context);

    // set the color
    CGFloat lineColor2[4] = {94.0f * colorFactor, 94.0f * colorFactor, 95.0f * colorFactor, 1.0f};
    CGContextSetStrokeColor(context, lineColor2);

    // left
    from = CGPointMake(200.0f, 1.0f);
    to = CGPointMake(200.0f, rect.size.height - 2.0f);
    [self addLineFrom:from to:to context:context];

    // bottom
    from = to;
    to = CGPointMake(rect.size.width - 2.0f, rect.size.height - 2.0f);
    [self addLineFrom:from to:to context:context];

    // right
    from = to;
    to = CGPointMake(rect.size.width - 2.0f, 1.0f);
    [self addLineFrom:from to:to context:context];

    // top
    from = to;
    to = CGPointMake(1.0f, 1.0f);
    [self addLineFrom:from to:to context:context];

    CGContextStrokePath(context);
}

2 个答案:

答案 0 :(得分:2)

如果内存服务,则默认情况下启用抗锯齿功能,这可能会导致更多像素受到绘图的影响而不是您想要的。关闭#{1}}的抗锯齿效果,看看是否有帮助。

的iOS:

CGContextRef

的Mac:

CGContextRef context = UIGraphicsGetCurrentContext();
[context setShouldAntialias:NO];

答案 1 :(得分:1)

第一个出现是一个像素厚,因为你已经在脏矩形的周边绘制了它,UIView为你剪裁了它,使它成为一个内部笔画。但实际上,两个矩形都有同样的问题

在另一个问题上,我写了a full description of the real problem and the real solutions。关闭AA就足够了直线,但是一旦你画了旋转或画一条对角线,你就会讨厌它。