天天看點

UIImage的旋轉

以下兩種方式都是用于UIImage的旋轉

+(UIImage *)rotate: (UIImage *)image

{

    double angle = 45;

    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;

}

+ (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;

}

繼續閱讀