2010-04-21 63 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將足以獲得直線,但是一旦您繪製旋轉或繪製對角線,您就會討厭它。