Search code examples
iosobjective-cuiimageviewcgaffinetransform

CGAffineTransformRotate on an UIImageView loads from Center


The App is in landscape mode and I have a UIButton, tapping which will attach UIImageView to the AppDelegate's window (for 'x' reasons). I tried applying the transform as shown in the code below, but the UIImageView does not attach to the top right corner, but near the center of the view.

-(IBAction)showFullScreenImage:(id)sender {
    if(_fullImageView==nil) {
        _fullImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.height,[UIScreen mainScreen].bounds.size.width)];
    }
    [self.fullImageView setImage:self.fullImage];
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageWasTapped:)];
    self.fullImageView.userInteractionEnabled = YES;
    AppDelegate * appDelegate = (AppDelegate * ) [UIApplication sharedApplication].delegate;
    [appDelegate.window addSubview:self.fullImageView];
    CGAffineTransform t = CGAffineTransformMakeTranslation(0,0);
    self.fullImageView.transform = CGAffineTransformRotate(t, -M_PI/2);
    NSLog(@"UIImageView frame:%@",NSStringFromCGRect(self.fullImageView.frame));
    [self.fullImageView addGestureRecognizer:gestureRecognizer]; 
}

-(void)imageWasTapped:(UIGestureRecognizer *)gestureRecognizer {
    if(gestureRecognizer.state==UIGestureRecognizerStateEnded) {
        [self.fullImageView removeFromSuperview];
    } 
}

The log prints out

UIImageView frame:{{124, -124}, {320, 568}}

What am I doing wrong here?


Solution

  • Fixed it myself.

    -(IBAction)showFullScreenImage:(id)sender {
        if(_fullImageView==nil) {
            _fullImageView = [[UIImageView alloc]initWithFrame:CGRectZero]; //init with zero
        }
        [self.fullImageView setImage:self.fullImage];
        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageWasTapped:)];
        self.fullImageView.userInteractionEnabled = YES;
        AppDelegate * appDelegate = (AppDelegate * ) [UIApplication sharedApplication].delegate;
        [appDelegate.window addSubview:self.fullImageView];
        self.fullImageView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, -M_PI/2);
        self.fullImageView.frame = [UIScreen mainScreen].bounds; //set it here
        [self.fullImageView addGestureRecognizer:gestureRecognizer];
    }