web-dev-qa-db-fra.com

Comment puis-je redimensionner l'imageView d'UIButton?

J'ai créé une instance UIButton nommée "bouton" avec une image utilisant [UIButton setImage:forState:]. Le button.frame est plus grand que la taille de l'image.

Maintenant, je veux redimensionner l'image de ce bouton. J'ai essayé de changer button.imageView.frame, button.imageView.bounds et button.imageView.contentMode, mais tout semble inefficace.

Quelqu'un peut-il m'aider à redimensionner l'imageView de UIButton?

J'ai créé le UIButton comme ceci:

UIButton *button = [[UIButton alloc] init];
[button setImage:image forState:UIControlStateNormal];

J'ai essayé de redimensionner l'image comme ceci:

button.imageView.contentMode = UIViewContentModeScaleAspectFit;
button.imageView.bounds = CGRectMake(0, 0, 70, 70);

et ça:

button.imageView.contentMode = UIViewContentModeScaleAspectFit;
button.imageView.frame = CGRectMake(0, 0, 70, 70);
74
vcLwei

Pour l'affiche originale, voici la solution que j'ai trouvée:

commentButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;

Cela permettra à votre bouton de redimensionner horizontalement. Il y a aussi un réglage vertical.

Il m'a fallu plusieurs heures pour comprendre que celui-ci (la dénomination de la propriété est très peu intuitif) était donc bien partagé.

86
Chris

J'avais un problème similaire: j'ai une image d'arrière-plan (une avec bordure) et une image (indicateur) pour un bouton personnalisé. Je voulais que le drapeau soit réduit et au centre. J'ai essayé de changer l'attribut de imageView mais je n'ai pas réussi et je voyais cette image - 

enter image description here

Au cours de mes expériences, j'ai essayé:

button.imageEdgeInsets = UIEdgeInsetsMake(kTop,kLeft,kBottom,kRight)

J'ai obtenu le résultat attendu en tant que: 

enter image description here

61
Hitesh Savaliya

Un moyen supplémentaire pour la configuration dans un fichier XIB . Vous pouvez choisir cette option si vous voulez que le texte ou l'image soit Rempli à l'échelle dans UIButton . Ce sera la même chose avec le code.

UIButton *btn = [UIButton new];

btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
btn.contentVerticalAlignment   = UIControlContentVerticalAlignmentFill;

 enter image description here

27
Linh Nguyen

utilisation 

button.contentMode = UIViewContentModeScaleToFill;

ne pas

button.imageView.contentMode = UIViewContentModeScaleAspectFit;

Mettre à jour:

Comme @Chris a commenté,

Pour que cela fonctionne pour setImage: forState:, vous devez procéder comme suit pour mettre à l'échelle horizontalement: myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;

22
pavelpanov
    UIButton *button= [[UIButton alloc] initWithFrame:CGRectMake(0,0,70,70)];
    button.buttonType = UIButtonTypeCustom;
    UIImage *buttonImage = [UIImage imageNamed:@"image.png"];

    UIImage *stretchableButtonImage = [buttonImage stretchableImageWithLeftCapWidth:12 topCapHeight:0]; 
    [button setBackgroundImage:stretchableButtonImage forState:UIControlStateNormal]; 
15
EEE

J'ai trouvé cette solution.

1) Sous-classe les méthodes suivantes de UIButton

+ (id)buttonWithType:(UIButtonType)buttonType {
    MyButton *toReturn = [super buttonWithType:buttonType];
    toReturn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    return toReturn;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    return contentRect;
}

Et ça marche bien.

10
marcio

Étrange, le seul combo qui a fonctionné pour moi (iOS 5.1) est ...

button.imageView.contentMode = UIViewContentModeScaleAspectFit;

et

[button setImage:newImage forState:UIControlStateNormal];

9
Hlung

Je viens de rencontrer ce même problème, et il y a une réponse possible à cette question:

Pourquoi une image UIButton personnalisée ne redimensionne-t-elle pas dans Interface Builder?

Pour l’essentiel, utilisez plutôt la propriété backgroundimage, qui est mise à l’échelle.

7
JosephH

Il suffit de faire (De Design OR De Code):

De la conception

  1. Ouvrez votre Storyboard xib OR.
  2. Bouton de sélection
  3. Inside Inspecteur d'attributs (côté droit)> Dans "Contrôle" section> sélectionne la dernière 4ème option pour Horizontal et Verique.

[Pour le point 3: modifier l’alignement horizontal et vertical en UIControlContentHorizontalAlignmentFill and UIControlContentVericalAlignmentFill]

À partir du code

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment =  UIControlContentVerticalAlignmentFill;
6
Sandip Patel - SM

comme cela peut résoudre votre problème:

+ (UIImage*)resizedImage:(UIImage*)image
{
 CGRect frame = CGRectMake(0, 0, 60, 60);
 UIGraphicsBeginImageContext(frame.size);
 [image drawInRect:frame];
 UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

 return resizedImage;
}
5
huangkui

De petit test que je viens de faire après avoir lu ici, cela dépend si vous utilisez setImage ou setBackgroundImage, les deux ont fait le même résultat et strech l'image

//for setBackgroundImage
 self.imageButton.contentMode = UIViewContentModeScaleAspectFill;
        [self.imageButton setBackgroundImage:[UIImage imageNamed:@"imgFileName"] forState:UIControlStateNormal];

//for setImage
 self.imageButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
        self.imageButton.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
    [self.imageButton setImage:[UIImage imageNamed:@"imgFileName"] forState:UIControlStateNormal];
5
user1105951
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment =  UIControlContentVerticalAlignmentFill;
4
iomar

Cela fonctionnera également, car backgroundImage est automatiquement redimensionné

[button setBackgroundImage:image forState:UIControlStateNormal];

1
Harris

_ImageView ne peut pas utiliser une solution, mais je peux utiliser une variable CGContextRef pour la résoudre. Il utilise UIGraphicsGetCurrentContext pour obtenir le currentContextRef et dessiner une image dans currentContextRef, puis redimensionner ou faire pivoter l'image et créer une nouvelle image. Mais ce n'est pas parfait.

le code:

-(UIImage*) scaleAndRotateImage:(UIImage*)photoimage width:(CGFloat)bounds_width height:(CGFloat)bounds_height;
{
    CGImageRef imgRef = photoimage.CGImage;

    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);

    bounds.size.width = bounds_width;
    bounds.size.height = bounds_height;

    CGFloat scaleRatio = bounds.size.width / width;
    CGFloat scaleRatioheight = bounds.size.height / height;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = photoimage.imageOrientation;
    switch(orient)
    {
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;

        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;

        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;

        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid?image?orientation"];
            break;
    }

    UIGraphicsBeginImageContext(bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft)
    {
        CGContextScaleCTM(context, -scaleRatio, scaleRatioheight);
        CGContextTranslateCTM(context, -height, 0);
    }
    else
    {
        CGContextScaleCTM(context, scaleRatio, -scaleRatioheight);
        CGContextTranslateCTM(context, 0, -height);
    }

    CGContextConcatCTM(context, transform);

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageCopy;
}
1
vcLwei

Storyboard

Vous devez définir une propriété spécifique dans Attributs d'exécution de Inspecteur d'identité - imageView.contentModel, où vous définissez une valeur relative à rawValue position de enum UIViewContentMode. 1 signifie scaleAspectFit.

 Set button.imageView.contentMode in Storyboard

Et l'alignement du bouton dans l'inspecteur Attributs:

 Full alignment of button

1
dimpiax

 Screenshot in XCode 8

En bas à gauche de la capture d'écran, vous pouvez voir les propriétés d'étirement. Essayez d'utiliser ceux-ci.

0
Harsh G.

J'espère que cela peut aider quelqu'un d'autre:

Swift 3+

button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.fill
button.contentVerticalAlignment =  UIControlContentVerticalAlignment.fill
0
Dasoga