Поверните изображение / контекст перед сохранением в файл - PullRequest
2 голосов
/ 20 июня 2011

Как мне повернуть мой контекст?

Я перепробовал все комбинации с CGAffineTransformRotate() и CGContextRotateCTM() Я мог придумать и не могу заставить его работать.

Кодниже работает хорошо.Он захватывает изображения различного размера с их фоном, чтобы они всегда были 320x480 или 480x320.Это важноТем не менее, я хочу, чтобы горизонтальные изображения поворачивались на 90 градусов непосредственно перед сохранением в файл.

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(480, 320), NO, 0.0);
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 480, 320)];           
    UIImage *im = [UIImage imageWithContentsOfFile:[allImagePaths objectAtIndex:currImg]];
    iv.image = im;
    iv.backgroundColor = [UIColor blackColor];
    iv.contentMode = UIViewContentModeScaleAspectFit;               
    CGContextRef context = UIGraphicsGetCurrentContext();       
    [iv.layer renderInContext:context];
        //
        // how to rotate it around here?
        //
    UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
    NSData* imageData = UIImageJPEGRepresentation(capturedImage, 1.0);
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    [imageData writeToFile:[docDir stringByAppendingPathComponent:@"result.jpg"] atomically:NO]; 
    UIGraphicsEndImageContext();

Каждый раз, когда я добавляю любой вид поворота, он просто прослушивается (белое изображение или только половина изображения на экране и не поворачивается).

Любая помощь с этим примером была бы хороша.

Ответы [ 3 ]

2 голосов
/ 20 июня 2011

Используйте этот метод категории для вдохновения.Это не будет делать то, что вы хотите, но идея та же.

- (UIImage *)fixOrientation 
{   
    // No-op if the orientation is already correct
    if (self.imageOrientation == UIImageOrientationUp) return self;

    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (self.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, self.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
    }

    switch (self.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
                                             CGImageGetBitsPerComponent(self.CGImage), 0,
                                             CGImageGetColorSpace(self.CGImage),
                                             CGImageGetBitmapInfo(self.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
            break;
    }

    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
1 голос
/ 21 июня 2011

Отстой, чтобы ответить на мой собственный вопрос, но хорошо ...

Кажется, главной проблемой была система координат.Вращение с CGContextRotateCTM() делает это вокруг (0,0) точки по умолчанию.Означает, что изображение «прячется» вне поля зрения.Я должен был сделать [image drawInRect:CGRectMake(0,-320,480,320)];.

Также мне пришлось использовать 2 контекста.Первый горизонтальный, чтобы захватить горизонтальное изображение с фоном.2-я вертикаль для сохранения повернутого изображения по вертикали.

0 голосов
/ 20 июня 2011

Попробуйте этот, еще не проверенный:

  CGSize size = imageIsHorizontal ? CGSizeMake(480, 320) : CGSizeMake(320, 480);
  UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextRotateCTM(context, 90 * M_PI / 180);
  [image drawInRect:(CGRect){CGPointZero, size}];
  UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  NSData* imageData = UIImageJPEGRepresentation(capturedImage, 1.0);
  NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  [imageData writeToFile:[docDir stringByAppendingPathComponent:@"result.jpg"] atomically:NO]; 
...