Search code examples
objective-cuibezierpathaffinetransform

Applying a scale and translate transformation to UIBezierPath


I have a UIBezierPath and I would like to:

  • Move to any coordinate on the UIView
  • Make bigger or smaller

I am drawing the UIBezierPath based off of a list of predefined coordinates. I implemented this code:

CGAffineTransform move = CGAffineTransformMakeTranslation(0, 0);

CGAffineTransform moveAndScale = CGAffineTransformScale(move, 1.0f, 1.0f);
[shape applyTransform:moveAndScale];

I have also tried scaling and then moving the shape, it seems to make little to no difference.

Using this code:

[shape moveToPoint:CGPointMake(0, 0)];  

I start drawing the shape at (0, 0), but this is what happens. I assume this is because a line is being drawn from 0, 0 to the next point in the list.

enter image description here

When I set the move transformation to (0, 0) this is where it draws. Here, moveToPoint is set to the first coordinate pair in the list. As you can see, it is not at 0, 0.

enter image description here

Finally, increasing the 1.0f moves the shape off the screen completely, no matter where the I tell the shape to move.

Can someone help me understand why the shape is not drawing at 0, 0 and why it moves off the screen when I scale it.


Solution

  • (As requested by the OP in a comment above)

    I might be wrong on this one, but doesn't this code

    CGAffineTransformMakeTranslation(0, 0);
    

    just say that something should be moved 0 pixels along the x-axis and 0 pixels along the y-axis? (reference) It won't actually move anything to origo (0, 0), as it seems you are trying to do.

    Also, it seems like you have slightly misunderstood how to properly use moveToPoint:.. Think of it as a way to move your cursor, but without actually drawing anything. It is just a way to say 'I want to start drawing at this point'. The drawing itself can be performed by other methods. If you wanted to e.g. draw a square with sides of length L, then you could do something like this..

    // 'shape' is a UIBezierPath
    NSInteger L = 100;
    CGPoint origin = CGPointMake(50, 50);
    [shape moveToPoint:origin]; // Initial point to draw from
    [shape addLineToPoint:CGPointMake(origin.x+L, origin.y)]; // Draw from origin to the right
    [shape addLineToPoint:CGPointMake(origin.x+L, origin.y+L)]; // Draw a vertical line
    [shape addLineToPoint:CGPointMake(origin.x, origin.y+L)]; // Draw bottom line
    [shape addLineToPoint:origin]; // Draw vertical line back to origin
    

    Note that this code is not tested at all, but it should give you the idea of how to use moveToPoint: and addLineToPoint:.