Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate image in UIImageView

Is it possible to rotate only image in UIImageView? I'm looking for information about it, but i only found information how rotate UIImageVeiw.

like image 765
gcalikpl Avatar asked Aug 25 '11 13:08

gcalikpl


2 Answers

You can rotate the image with the following code. Note, this uses a CGImageRef which you can get from a UIImage via

CGImageRef imageRef = [self CGImageRotatedByAngle:[image CGImage] angle:30];

Once you get the rotated image, you can set the ImageView's image to your new rotated image like this:

UIImage* img = [UIImage imageWithCGImage: imageRef];
myImageView.image = img;

here is a method that will rotate the imageRef:

- (CGImageRef)CGImageRotatedByAngle:(CGImageRef)imgRef angle:(CGFloat)angle
{

    CGFloat angleInRadians = angle * (M_PI / 180);
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGRect imgRect = CGRectMake(0, 0, width, height);
    CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians);
    CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform);

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef bmContext = CGBitmapContextCreate(NULL,
                                                   rotatedRect.size.width,
                                                   rotatedRect.size.height,
                                                   8,
                                                   0,
                                                   colorSpace,
                                                   kCGImageAlphaPremultipliedFirst);
    CGContextSetAllowsAntialiasing(bmContext, YES);
    CGContextSetShouldAntialias(bmContext, YES);
    CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh);
    CGColorSpaceRelease(colorSpace);
    CGContextTranslateCTM(bmContext,
                          +(rotatedRect.size.width/2),
                          +(rotatedRect.size.height/2));
    CGContextRotateCTM(bmContext, angleInRadians);
    CGContextTranslateCTM(bmContext,
                          -(rotatedRect.size.width/2),
                          -(rotatedRect.size.height/2));
    CGContextDrawImage(bmContext, CGRectMake(0, 0,
                                             rotatedRect.size.width,
                                             rotatedRect.size.height),
                       imgRef);



    CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
    CFRelease(bmContext);
    [(id)rotatedImage autorelease];

    return rotatedImage;
}
like image 72
cdasher Avatar answered Oct 05 '22 08:10

cdasher


Take a look at rotating the ImageView's layer. You will need to import the QuartzCore library to make that accessible.

myImageView.layer.transform = CGAffineTransformMakeRotation (1.5);
like image 27
Dancreek Avatar answered Oct 05 '22 08:10

Dancreek