Question

I am using the following code to achieve this. The problem is when the image is rotated it scales the image the nearer the degree is to 45'.

When the image is set to 90' and its multiples there is no problem with the image size. But when the degree gets close to 45' and its multiples there is a noticeable shrink in the image size. I do not want to change the image size. How should I approach this problem?

- (UIImage *)imageRotatedByRadians:(CGFloat)radians img:(UIImage *)img
{
    // calculate the size of the rotated view's containing box for our drawing space
    UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,img.size.width, img.size.height)];
    UIView *nonrotatedViewBox = rotatedViewBox;
    CGAffineTransform t = CGAffineTransformMakeRotation(radians);
    rotatedViewBox.transform = t;
    CGSize rotatedSize = rotatedViewBox.frame.size;

    // Create the bitmap context
    UIGraphicsBeginImageContext(nonrotatedViewBox.frame.size);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();

    // Move the origin to the middle of the image so we will rotate and scale around the center.
    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

    //Rotate the image context
    CGContextRotateCTM(bitmap, radians);

    // Now, draw the rotated/scaled image into the context
    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-img.size.width / 2, -img.size.height / 2, img.size.width, img.size.height), [img CGImage]);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
Was it helpful?

Solution

the dimensions of your view are wrong, you don't want to draw the image in the width and height divided by 2. Because when an image is rotated it's width becomes (when referring to a perfect square) is the width times 2 times sqr(2). so if you had a width and height of like 10 then your new width (at a 45 degree angle) would be between 14 and 15... so your context is drawing a 14x14 image in a 10x10 area

you could go through some complicated math to get the perfect dimensions using geometry, or you could wing it and say | double percentRotated = (radians % M_PI_4)/M_PI_4; double newWidth = (percentRotated == 0 ? img.size.width : img.size.width * (1 + (percentRotated % 0.25)) ); and do the same thing for the height, #lazyprogrammer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top