slider
slider

Reputation: 2816

Is there a better alternative to CGContext?

I'm creating a funnel shape using CGContext, by first drawing a triangle, followed by a line. I'm implementing this in drawRect of my UIView subclass, but wondering if there is an alternative way of drawing this, because the lines are a bit blurry.

    override func drawRect(rect: CGRect) {

        let context: CGContextRef = UIGraphicsGetCurrentContext()!
        CGContextClearRect(context, rect);

        let rectWidth: CGFloat = 15

        // Line
        CGContextSetRGBStrokeColor(context, 0, 0, 0, 1)
        CGContextMoveToPoint(context, rectWidth / 2, 5)
        CGContextAddLineToPoint(context, rectWidth / 2, 10)
        CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor)
        CGContextSetLineCap(context, CGLineCap.Round)
        CGContextSetLineWidth(context, 3.0)
        CGContextStrokePath(context)

        // Triangle
        CGContextBeginPath(context);
        CGContextMoveToPoint   (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
        CGContextAddLineToPoint(context, CGRectGetMidX(rect), 8);
        CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMinY(rect));
        CGContextClosePath(context);

        UIColor.blueColor().setFill()
        CGContextFillPath(context);

    }

Produces this: enter image description here

But when I import an image that I designed, the image is crisper (you can tell on an iPhone): enter image description here

So, is there a better way of achieving this output? The CGContext lines are a bit blurry, so I'd like to know if there is a better alternative and what the pros and cons to those methods are.

Upvotes: 2

Views: 389

Answers (1)

rickster
rickster

Reputation: 126127

Core Graphics is drawing things blurry probably because you told it to. The location of each pair of integer coordinates in the CG coordinate system is exactly on the grid lines — if you draw a one point wide stroke between such coordinates, you get a stroke that straddles the grid line by half a point on either side. Depending on the scale of the bitmap context you're drawing into, that could result in two columns of half-shaded pixels instead of one column of fully-shaded pixels — that is, a blurry line.

In your case, some of the points you're drawing lines between fall on whole-pixel boundaries and some on half-pixel boundaries, so on 1x displays some of the lines will be blurry and on 2x or 3x displays others will be. Read about Points versus Pixels in Apple's docs on drawing, and you'll probably find a way to offset your coordinates that makes the lines all fall where you want them to.

Upvotes: 4

Related Questions