Konrad77
Konrad77

Reputation: 2535

Rotate UIView and keep aspect ratio after rotation

I want to rotate a UIView, but after the rotation the view is resized. I am using the autoresizing flag 'UIViewAutoresizingNone'.

Here is my code: (called from layoutSubViews)

- (void) setVerticalLabelFrame:(CGRect)r {

r.origin.y +=100.0f;
r.size.height = 20.0f;
r.size.width = 180.0f;
[[self rotatatingView] setFrame:r];
//[[self rotatatingView] setTransform:CGAffineTransformMakeRotation(M_PI / 4.0f)];

}

Here is the lazy initialization of the rotatingView.

- (UIView*)rotatatingView {
if (rotatatingView == nil) {
    rotatatingView = [[UIView alloc] initWithFrame:CGRectZero];
    [rotatatingView setBackgroundColor:[UIColor orangeColor]];
    [rotatatingView setAutoresizingMask:UIViewAutoresizingNone];
    [[self imageView] addSubview:rotatatingView];
}
return rotatatingView;

}

First shot is with the last line commented, second shot with the line uncommented. Any ideas?

enter image description here enter image description here

Upvotes: 1

Views: 1498

Answers (1)

mattjgalloway
mattjgalloway

Reputation: 34902

You need to be setting the bounds & center if you're setting a non-identity transformation matrix. As per the docs:

Warning If this property is not the identity transform, the value of the frame property is undefined and therefore should be ignored.

So try something like this:

- (void) setVerticalLabelFrame:(CGRect)r {
    CGRect bounds = CGRectZero;
    bounds.size.height = 20.0f;
    bounds.size.width = 180.0f;

    CGPoint center;
    center.x = r.origin.x + (bounds.size.width / 2.0f);
    center.x = r.origin.y + (bounds.size.height / 2.0f) + 100.0f;

    [[self rotatingView] setTransform:CGAffineTransformIdentity];

    [[self rotatingView] setCenter:center];
    [[self rotatingView] setBounds:bounds];

    [[self rotatingView] setTransform:CGAffineTransformMakeRotation(M_PI / 4.0f)];
}

Upvotes: 1

Related Questions