Search code examples
iphoneuiviewcore-graphicscgaffinetransform

Bounds of a rotated UIView and Core Graphics


I have a subclass of UIView which is drawing a location icon. When I rotate the view a few degrees it's bounds (highlighted in green using CGContextAddRect) seem to change drastically causing my drawing to look distorted.


(source: bytolution.com)


(source: bytolution.com)

Here's my code:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.locationTagView.frame = CGRectMake(40, 80, 240, 240);
    CGAffineTransform transform = CGAffineTransformMakeRotation(DegreesToRadians(30));
    self.locationTagView.transform = transform;
    [self.view addSubview:self.locationTagView];
}

Solution

  • This fixes it:

    #define LOCTAG_HEIGHT 240
    #define LOCTAG_WIDTH 240
    
    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
        self.locationTagView.frame = CGRectMake(40, 80, LOCTAG_WIDTH, LOCTAG_HEIGHT);
        self.locationTagView.bounds = CGRectMake(0, 0, LOCTAG_WIDTH, LOCTAG_HEIGHT);
        CGAffineTransform transform = CGAffineTransformMakeRotation(DegreesToRadians(340));
        self.locationTagView.transform = transform;
        [self.view addSubview:self.locationTagView];
    }
    


    (source: bytolution.com)

    Setting the bounds separately makes it work!