Kex
Kex

Reputation: 8579

Resizing a UIView but drawing done by drawRect also changing size

I am testing a UIView using a UISlider as in the example images below:

enter image description here

enter image description here

I have a custom UIView with a yellow background that draws the gray square, the drawRect method is like so:

-(void)drawRect:(CGRect)rect{

    NSLog(@"Draw rect called");

    UIBezierPath* squarePath = [UIBezierPath bezierPathWithRect: CGRectMake(10, 10, 100, 100)];
    [UIColor.grayColor setFill];
    [squarePath fill];
}

And the method for my slide changing value:

- (IBAction)changeValue:(id)sender {

    CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, self.slider.value, self.slider.value);
    self.tableView.transform = transform;
    [self.tableView setNeedsDisplay];



}

I dont understand why the square is getting larger. I've noticed that drawRect is called every time the slider is moved. If this happens then why is the square size changing? Shouldn't it remain the same size and just the frame grow with the square in the top left corner?

My second question is, how would I change the code so just the frame grows and the drawing size stays the same? I ask this because actually I want the drawing size to change dynamically using my own code in drawRect.

Any pointers would be really appreciated! thanks!

Upvotes: 1

Views: 963

Answers (1)

Metabble
Metabble

Reputation: 11841

The reason why the size of the square changes is because you've transformed it. Transformations don't just affect the frame of a view; they will affect the content. The square is getting drawn into its context at its constant size (100x100) and then the transform is stretching it before it gets rendered.

The reason why it's not expanding to the right and down is because by default the anchor point of a transform is the center of the bounds. Thus it'll scale from the center outwards. From the documentation:

The origin of the transform is the value of the center property ...

Transformations aren't intended to be used to simply scale the width and height of your frame. The frame property is for that. Simply store the view's frame in a variable, change its width and height, then set it back. In your drawRect: code you can check the dimensions of the rectangle that's given to you and make your square's width/height a percentage of that.

Upvotes: 2

Related Questions