Cette méthode fera ce que vous voulez et est une catégorie de UIImage pour la facilité d'utilisation. Je suis allé avec redimensionner puis recadrer, vous pouvez changer le code assez facilement si vous voulez recadrer puis redimensionner. Les bornes vérifiant la fonction sont purement illustratives. Vous voudrez peut-être faire quelque chose de différent, par exemple, centrer le rectangle de récolte par rapport aux dimensions de outputImage, mais cela devrait vous permettre de vous rapprocher suffisamment pour effectuer les autres changements dont vous avez besoin.
@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
+1 Choix, j'ai besoin d'aide maintenant. Si vous avez la réponse signifie pls Poster la réponse, Bcoz j'ai besoin de la même chose yar ** Pls ** !! –
+1 Pour une présentation détaillée – shashwat