2010-04-21 64 views
2

我尝试绘制一些不同颜色的线条。为什么我的线条越来越厚?

此代码尝试绘制两个具有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); 
} 
+0

线增粗:它影响到我们所有人! :-) – Smandoli 2010-04-21 16:34:21

+0

我应该猜什么?或者你是说这些线条粗细问题很常见? – dontWatchMyProfile 2010-04-21 16:40:54

回答

2

如果没记错,抗锯齿是在默认情况下可能会导致更多的像素比你打算通过绘图的影响。为您的CGContextRef关闭抗锯齿功能,看看是否有帮助。

的iOS:

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

的Mac:

CGContextRef context = [NSGraphicsContext currentContext]; 
[context setShouldAntialias:NO]; 
+0

如何关闭CGContextRef的抗锯齿功能? – harshit2811 2012-02-01 07:10:00

+5

'CGContextSetAllowsAntialiasing(context,false);'禁用'CGContextRef'的抗锯齿。 – Raginmari 2012-08-11 19:34:20

1

第一个出现是一个像素厚,因为你已经绘制它周围的脏矩形的边界,这UIView的剪辑为了你,让它成为中风。但是,实际上,这两个矩形都有相同的问题

关于另一个问题,我写了a full description of the real problem and the real solutions。关闭AA将足以获得直线,但是一旦您绘制旋转或绘制对角线,您就会讨厌它。