现在的位置: 首页 > 综合 > 正文

UIImage的旋转

2013年03月05日 ⁄ 综合 ⁄ 共 1984字 ⁄ 字号 评论关闭
- (UIImage *) rotate: (UIImage *) image
{
    double angle = 20;
    CGSize s = {image.size.width, image.size.height};
    UIGraphicsBeginImageContext(s);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(ctx, 0,image.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);

    CGContextRotateCTM(ctx, 2*M_PI*angle/360);
    CGContextDrawImage(ctx,CGRectMake(0,0,image.size.width, image.size.height),image.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;

}
#pragma mark -
#pragma mark Rotate Image 

- (UIImage *)scaleAndRotateImage:(UIImage *)image  { 

    CGImageRef imgRef = image.CGImage;

    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);

    CGFloat boundHeight;

    boundHeight = bounds.size.height;  
    bounds.size.height = bounds.size.width; 
    bounds.size.width = boundHeight;
    transform = CGAffineTransformMakeScale(-1.0, 1.0);
    transform = CGAffineTransformRotate(transform, M_PI / 2.0); //use angle/360 *MPI

    UIGraphicsBeginImageContext(bounds.size);   
    CGContextRef context = UIGraphicsGetCurrentContext();   
    CGContextConcatCTM(context, transform); 
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;   

}
- (UIImage *)rotate:(UIImage *)image radians:(float)rads
{
    float newSide = MAX([image size].width, [image size].height);
    CGSize size =  CGSizeMake(newSide, newSide);
    UIGraphicsBeginImageContext(size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(ctx, newSide/2, newSide/2);
    CGContextRotateCTM(ctx, rads);
    CGContextDrawImage(UIGraphicsGetCurrentContext(),CGRectMake(-[image size].width/2,-[image size].height/2,size.width, size.height),image.CGImage);
    //CGContextTranslateCTM(ctx, [image size].width/2, [image size].height/2);

    UIImage *i = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return i;
}

转帖:http://stackoverflow.com/questions/5102474/rotate-uiimage-custom-degree

抱歉!评论已关闭.