0

I want to implement freeform drawing in my app. First, I tried the code inside drawLayer:inContext: and it gave me the result I wanted.

Drawing in CALayer:

CALayer drawing implementation

But when I decided to implement the code inside drawRect:, this happened:

drawing implemented in drawRect: method

Even if I draw inside the white space, the drawing is rendered outside as shown above. The code I used is exactly the same. I copy-pasted it from drawLayer:inContext: to drawRect:. I didn't change a thing, so why is this happening?

The Code:

CGContextSaveGState(ctx);

CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetLineWidth(ctx, 1.0);
CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1);
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, prevPoint.x, prevPoint.y);
for (NSValue *r in drawnPoints){
    CGPoint pt = [r CGPointValue];
    CGContextAddLineToPoint(ctx, pt.x, pt.y);
}
CGContextStrokePath(ctx);

CGContextRestoreGState(ctx);
Anna Fortuna
  • 1,071
  • 2
  • 17
  • 33

1 Answers1

0

I see you are using app in full screen mode where the view is centered and does not take full width of the screen.

It may be that CALayer has transform applied to it that translates the drawing from the left side of the screen to the center. This may not be the case with drawRect:. Try setting CGContext's transform matrix:

CGContextSaveGState(ctx);
CGFloat xOffset = CGRectGetMidX(screenFrame) - CGRectGetMidX(viewFrame);
CGContextTranslateCTM(ctx, xOffset, 0.0f);
// rest of drawing code
// ...
CGContextRestoreGState(ctx);
Eimantas
  • 48,927
  • 17
  • 132
  • 168
  • I'm sorry but what is the difference of the screen frame from the view frame? – Anna Fortuna Jul 09 '12 at 07:51
  • What I did is this `CGFloat xOffset = CGRectGetMidX(self.frame) - CGRectGetMidX(contentView.frame)` where `contentView` is the white page where I want to draw. I can draw anywhere in the UIView, *except* for the `contentView` itself. It's like it is "hovering" above the view. – Anna Fortuna Jul 09 '12 at 08:05