Подтвердить что ты не робот

Изменять размер и обрезать изображение по центру

поэтому в настоящее время я пытаюсь обрезать и изменять размер изображения, чтобы он соответствовал определенному размеру, не теряя при этом отношения.

небольшое изображение, чтобы показать, что я имею в виду:

alt text

Я немного играл с категориями vocaro, но они не работают с png и имеют проблемы с gif. также изображение не обрезается.

Есть ли у кого-нибудь предложение, как это изменить размер наилучшим образом или, возможно, иметь ссылку на существующую библиотеку/категорию/независимо?

спасибо за все подсказки!

p.s.: ios реализует "выбрать выдержку", чтобы у меня было правильное соотношение и нужно было только масштабировать?!

4b9b3361

Ответ 1

Этот метод будет делать то, что вы хотите, и является категорией UIImage для удобства использования. Я пошел с изменением размера, затем обрезал, вы могли бы легко переключить код, если хотите, чтобы затем урожай изменился. Проверка границ в функции является чисто иллюстративной. Возможно, вы захотите сделать что-то другое, например, центрировать обрезание по отношению к размерам outputImage, но это должно быть достаточно близко, чтобы сделать любые другие изменения, которые вам нужны.

@implementation UIImage( resizeAndCropExample )

- (UIImage *) resizeToSize:(CGSize) newSize thenCropWithRect:(CGRect) cropRect {
    CGContextRef                context;
    CGImageRef                  imageRef;
    CGSize                      inputSize;
    UIImage                     *outputImage = nil;
    CGFloat                     scaleFactor, width;

    // resize, maintaining aspect ratio:

    inputSize = self.size;
    scaleFactor = newSize.height / inputSize.height;
    width = roundf( inputSize.width * scaleFactor );

    if ( width > newSize.width ) {
        scaleFactor = newSize.width / inputSize.width;
        newSize.height = roundf( inputSize.height * scaleFactor );
    } else {
        newSize.width = width;
    }

    UIGraphicsBeginImageContext( newSize );

    context = UIGraphicsGetCurrentContext();

    // added 2016.07.29, flip image vertically before drawing:
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0, newSize.height);
    CGContextScaleCTM(context, 1, -1);
    CGContextDrawImage(context, CGRectMake(0, 0, newSize.width, newSize.height, self.CGImage);

//  // alternate way to draw
//  [self drawInRect: CGRectMake( 0, 0, newSize.width, newSize.height )];

    CGContextRestoreGState(context);

    outputImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    inputSize = newSize;

    // constrain crop rect to legitimate bounds
    if ( cropRect.origin.x >= inputSize.width || cropRect.origin.y >= inputSize.height ) return outputImage;
    if ( cropRect.origin.x + cropRect.size.width >= inputSize.width ) cropRect.size.width = inputSize.width - cropRect.origin.x;
    if ( cropRect.origin.y + cropRect.size.height >= inputSize.height ) cropRect.size.height = inputSize.height - cropRect.origin.y;

    // crop
    if ( ( imageRef = CGImageCreateWithImageInRect( outputImage.CGImage, cropRect ) ) ) {
        outputImage = [[[UIImage alloc] initWithCGImage: imageRef] autorelease];
        CGImageRelease( imageRef );
    }

    return outputImage;
}

@end

Ответ 2

Я столкнулся с одной и той же проблемой в одном из своих приложений и разработал этот фрагмент кода:

+ (UIImage*)resizeImage:(UIImage*)image toFitInSize:(CGSize)toSize
{
    UIImage *result = image;
    CGSize sourceSize = image.size;
    CGSize targetSize = toSize;

    BOOL needsRedraw = NO;

    // Check if width of source image is greater than width of target image
    // Calculate the percentage of change in width required and update it in toSize accordingly.

    if (sourceSize.width > toSize.width) {

        CGFloat ratioChange = (sourceSize.width - toSize.width) * 100 / sourceSize.width;

        toSize.height = sourceSize.height - (sourceSize.height * ratioChange / 100);

        needsRedraw = YES;
    }

    // Now we need to make sure that if we chnage the height of image in same proportion
    // Calculate the percentage of change in width required and update it in target size variable.
    // Also we need to again change the height of the target image in the same proportion which we
    /// have calculated for the change.

    if (toSize.height < targetSize.height) {

        CGFloat ratioChange = (targetSize.height - toSize.height) * 100 / targetSize.height;

        toSize.height = targetSize.height;
        toSize.width = toSize.width + (toSize.width * ratioChange / 100);

        needsRedraw = YES;
    }

    // To redraw the image

    if (needsRedraw) {
        UIGraphicsBeginImageContext(toSize);
        [image drawInRect:CGRectMake(0.0, 0.0, toSize.width, toSize.height)];
        result = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    // Return the result

    return result;
}

Вы можете изменить его в соответствии с вашими потребностями.