Comment mettre à l'échelle L'imageView D'UIButton?

j'ai créé une instance UIButton nommée" button "avec une image utilisant [UIButton setImage:forState:] . Bouton.le cadre est plus grand que la taille de l'image.

maintenant je veux réduire l'image de ce bouton. J'ai essayé de changer button.imageView.frame , button.imageView.bounds et button.imageView.contentMode , mais tous semblent inefficaces.

est-ce que quelqu'un peut m'aider à mettre à l'échelle un UIButton 's imageView?

j'ai créé le UIButton comme ceci:

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

j'ai essayé de dimensionner l'image comme ceci:

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

et ceci:

button.imageView.contentMode = UIViewContentModeScaleAspectFit;
button.imageView.frame = CGRectMake(0, 0, 70, 70);
74
demandé sur Pang 2009-12-24 11:09:16

17 réponses

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

commentButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;

cela permettra à votre bouton de se décaler horizontalement. Il y a une verticale.

m'a pris plusieurs heures pour comprendre qu'un out (le nom de la propriété est très peu intuitif) donc pensé que je partagerais.

85
répondu Chris 2011-11-18 08:56:24

j'ai rencontrés le même problème, j'ai une Image de fond (avec bordure) et une image (drapeau) pour un bouton personnalisé. Je voulais que le drapeau soit réduit et au centre. J'ai essayé de changer l'attribut d'imageView, mais je n'ai pas réussi et j'ai vu cette image ...

enter image description here

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

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

résultat obtenu:

enter image description here

61
répondu Hitesh Savaliya 2013-09-03 09:24:06

une façon supplémentaire pour la configuration dans le fichier XIB. Vous pouvez choisir cette option si vous voulez que le texte ou l'image soit mis à L'échelle. Ce sera la même chose avec le code.

UIButton *btn = [UIButton new];

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

enter image description here

25
répondu Linh Nguyen 2015-12-16 04:27:57

utiliser

button.contentMode = UIViewContentModeScaleToFill;

pas

button.imageView.contentMode = UIViewContentModeScaleAspectFit;

mise à jour:

comme @Chris l'a commenté,

pour que cela fonctionne pour setImage:forState:, vous devez faire ce qui suit à l'échelle horizontale: myButton.contenthorizontalalalignment = UIControlContentHorizontalAlignmentfill;

22
répondu pavelpanov 2014-11-07 05:35:51
    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
répondu EEE 2009-12-24 08:23:09

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
répondu marcio 2014-06-17 13:02:09

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

button.imageView.contentMode = UIViewContentModeScaleAspectFit;

et

[button setImage:newImage forState:UIControlStateNormal];

9
répondu Hlung 2012-05-16 07:05:01

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 pas dans Interface Builder?

essentiellement, utilisez la propriété backgrounddimage à la place, qui ne se redimensionnera pas.

7
répondu JosephH 2017-05-23 11:54:47

Just do (De la Conception OU De Code):

Du Modèle

  1. ouvrez votre XIB ou Storyboard.
  2. , Sélectionnez le bouton
  3. à l'Intérieur "1519120920 Attribut" Inspecteur (à Droite) > Dans "Contrôle" "1519130920 de la section" > sélectionner le dernier 4ème option pour à la fois Horizontale et Verical.

[Pour Le Point 3: Changement Alignement Horizontal et vertical sur UIControlContentHorizontalAlignmentFill and UIControlContentVericalAlignmentFill]

Du Code

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment =  UIControlContentVerticalAlignmentFill;
6
répondu Sandip Patel - SM 2016-08-04 11:18:44

comme ceci 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
répondu huangkui 2011-05-27 18:13:35

de petit test que je viens de faire après avoir lu ici, 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
répondu user1105951 2014-06-17 13:02:28
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment =  UIControlContentVerticalAlignmentFill;
4
répondu iomar 2014-06-17 12:58:50

Je ne peux pas obtenir une utilisation de solution par _imageView, mais je peux utiliser un CGContextRef pour le résoudre. Il utilise le UIGraphicsGetCurrentContext pour obtenir le currentContextRef et dessiner une image dans currentContextRef, puis l'échelle ou la rotation de l'image et de créer une nouvelle image. Mais il 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
répondu vcLwei 2014-06-17 12:59:17

cela fonctionnera aussi, car le background bascule automatiquement

[button setBackgroundImage:image forState:UIControlStateNormal];

1
répondu Harris 2016-03-16 22:17:48

Storyboard

vous devez définir une propriété spécifique dans Runtime Attributes de Identity inspector imageView.contentModel , où vous définissez la valeur relative à rawValue position de l'enum UIViewContentMode . 1 signifie scaleAspectFit .

Set button.imageView.contentMode in Storyboard

et alignement du bouton, dans les attributs inspecteur :

Full alignment of button

1
répondu dimpiax 2017-10-02 20:33:48

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
répondu Harsh G. 2017-08-15 19:29:30

chaque UIButton a sa propre UIImageView cachée. Nous devons donc régler le mode contenu comme indiqué ci-dessous...

[[btn imageView] setContentMode: UIViewContentModeScaleAspectFit];
[btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
-1
répondu emraz 2017-07-15 12:12:36