2010-10-17 6 views
16

donc actuellement j'essaie de recadrer et de redimensionner une image pour l'adapter à une taille spécifique sans perdre le ratio.redimensionner et recadrer l'image centrée

une petite image pour montrer ce que je veux dire:

alt text

j'ai joué un peu avec vocaro's categories mais ils ne fonctionnent pas avec png et ont des problèmes avec gifs. De plus, l'image n'est pas recadrée.

Quelqu'un a-t-il une suggestion sur la façon de redimensionner le plus efficacement possible ou d'avoir probablement un lien vers une bibliothèque/catégorie/autre existante?

merci pour tous les conseils!

p.s .: est-ce que ios implémente un "select a extrait" de sorte que j'ai le bon ratio et n'ai qu'à l'agrandir?!

+0

+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 ** !! –

+0

+1 Pour une présentation détaillée – shashwat

Répondre

7

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 
+4

J'ai testé votre code et il fait pivoter mon image de 180 degrés. – VansFannel

+0

Votre vue est-elle inversée? Ce code fonctionne correctement pour les vues standard. Si elle est inversée, vous devrez peut-être modifier la matrice de transformation actuelle. – par

+0

Downvoters: quel est le problème? Cela a très bien fonctionné en 2010. – par

2

Je suis tombé sur ont le même problème dans l'un de ma demande et développé ce morceau de code:

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

Vous pouvez le modifier en fonction de vos besoins.

+1

merci d'ajouter cette – choise

Questions connexes