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);
}
4

2 回答 2

2

如果没有记错的话,默认情况下会启用抗锯齿功能,这可能会导致您的绘图影响的像素多于您的预期。为您关闭抗锯齿CGContextRef,看看是否有帮助。

IOS:

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

苹果电脑:

CGContextRef context = [NSGraphicsContext currentContext];
[context setShouldAntialias:NO];
于 2010-04-21T16:40:33.697 回答
1

第一个似乎是一个像素厚,因为您已经在脏矩形的周边绘制了它,UIView 为您剪裁了它,使其成为内部笔划。但是,事实上,两个矩形都有同样的问题

On another question, I wrote a full description of the real problem and the real solutions. Turning off AA will suffice for straight lines, but you'll hate it as soon as you draw rotated or draw a diagonal.

于 2010-04-23T01:40:59.800 回答