我有一个UIImage(UIImageOrientationUp纵向),我想逆时针旋转 90 度(横向)。我不想使用CGAffineTransform. 我希望 的像素UIImage实际移动位置。我正在使用一段代码(如下所示),最初是为了调整 a 的大小UIImage来做到这一点。我将目标大小设置为当前大小,UIImage但出现错误:
UIImage
UIImageOrientationUp
CGAffineTransform
(错误):CGBitmapContextCreate:无效数据字节/行:对于 8 个整数位/分量、3 个分量、kCGImageAlphaPremultipliedLast,应至少为 1708。
(每当我提供一个较小的尺寸作为目标尺寸 BTW 时,我都不会收到错误消息)。如何UIImage在保留当前大小的同时仅使用核心图形功能旋转 90 度 CCW?
-(UIImage*)reverseImageByScalingToSize:(CGSize)targetSize:(UIImage*)anImage { UIImage* sourceImage = anImage; CGFloat targetWidth = targetSize.height; CGFloat targetHeight = targetSize.width; CGImageRef imageRef = [sourceImage CGImage]; CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef); if (bitmapInfo == kCGImageAlphaNone) { bitmapInfo = kCGImageAlphaNoneSkipLast; } CGContextRef bitmap; if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) { bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); } else { bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); } if (sourceImage.imageOrientation == UIImageOrientationRight) { CGContextRotateCTM (bitmap, radians(90)); CGContextTranslateCTM (bitmap, 0, -targetHeight); } else if (sourceImage.imageOrientation == UIImageOrientationLeft) { CGContextRotateCTM (bitmap, radians(-90)); CGContextTranslateCTM (bitmap, -targetWidth, 0); } else if (sourceImage.imageOrientation == UIImageOrientationDown) { // NOTHING } else if (sourceImage.imageOrientation == UIImageOrientationUp) { CGContextRotateCTM (bitmap, radians(90)); CGContextTranslateCTM (bitmap, 0, -targetHeight); } CGContextDrawImage(bitmap, CGRectMake(0, 0, targetWidth, targetHeight), imageRef); CGImageRef ref = CGBitmapContextCreateImage(bitmap); UIImage* newImage = [UIImage imageWithCGImage:ref]; CGContextRelease(bitmap); CGImageRelease(ref); return newImage; }
怎么样的东西:
static inline double radians (double degrees) {return degrees * M_PI/180;} UIImage* rotate(UIImage* src, UIImageOrientation orientation) { UIGraphicsBeginImageContext(src.size); CGContextRef context = UIGraphicsGetCurrentContext(); if (orientation == UIImageOrientationRight) { CGContextRotateCTM (context, radians(90)); } else if (orientation == UIImageOrientationLeft) { CGContextRotateCTM (context, radians(-90)); } else if (orientation == UIImageOrientationDown) { // NOTHING } else if (orientation == UIImageOrientationUp) { CGContextRotateCTM (context, radians(90)); } [src drawAtPoint:CGPointMake(0, 0)]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }