titlelabel color buttons objective-c ios uibutton

objective c - color - ¿Escalar imagen en un UIButton para AspectFit?



menu ios (14)

Ampliando la respuesta de Dave, puede establecer el modo de contentMode de la imagen del botón imageView todo en IB, sin ningún código, utilizando los atributos de tiempo de ejecución:

  • 1 significa UIViewContentModeScaleAspectFit ,
  • 2 significaría UIViewContentModeScaleAspectFill .

Quiero agregar una imagen a un UIButton, y también quiero escalar mi imagen para que coincida con el UIButton (hacer que la imagen sea más pequeña). Por favor muéstrame cómo hacerlo.

Esto es lo que he intentado, pero no funciona:

  • Agregar imagen al botón y usar setContentMode :

[self.itemImageButton setImage:stretchImage forState:UIControlStateNormal]; [self.itemImageButton setContentMode:UIViewContentModeScaleAspectFit];

  • Hacer una "imagen elástica":

UIImage *stretchImage = [updatedItem.thumbnail stretchableImageWithLeftCapWidth:0 topCapHeight:0];


Esto ahora puede hacerse a través de las propiedades UIButton de IB. La clave es establecer su imagen como fondo, de lo contrario no funcionará.


La forma más fácil de establecer programáticamente un UIButton imageView en modo de ajuste de aspecto :

Rápido

button.contentHorizontalAlignment = .fill button.contentVerticalAlignment = .fill button.imageView?.contentMode = .scaleAspectFit

C objetivo

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill; button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill; button.imageView.contentMode = UIViewContentModeScaleAspectFit;

Nota: Puede cambiar .scaleAspectFit (UIViewContentModeScaleAspectFit) a .scaleAspectFill (UIViewContentModeScaleAspectFill) para establecer un modo de relleno de aspecto


La imagen de fondo se puede configurar para escalar el relleno de aspecto con bastante facilidad. Solo necesito hacer algo como esto en una subclase de UIButton:

- (CGRect)backgroundRectForBounds:(CGRect)bounds { // you''ll need the original size of the image, you // can save it from setBackgroundImage:forControlState return CGRectFitToFillRect(__original_image_frame_size__, bounds); } // Utility function, can be saved elsewhere CGRect CGRectFitToFillRect( CGRect inRect, CGRect maxRect ) { CGFloat origRes = inRect.size.width / inRect.size.height; CGFloat newRes = maxRect.size.width / maxRect.size.height; CGRect retRect = maxRect; if (newRes < origRes) { retRect.size.width = inRect.size.width * maxRect.size.height / inRect.size.height; retRect.origin.x = roundf((maxRect.size.width - retRect.size.width) / 2); } else { retRect.size.height = inRect.size.height * maxRect.size.width / inRect.size.width; retRect.origin.y = roundf((maxRect.size.height - retRect.size.height) / 2); } return retRect; }


La solución más limpia es usar diseño automático . UIButton prioridad de resistencia a la compresión de contenido de mi UIButton y configuré la imagen (no la imagen de fondo ) a través de Interface Builder . Después de eso agregué un par de restricciones que definen el tamaño de mi botón (bastante complejo en mi caso) y funcionó a las mil maravillas.


Ninguna de las respuestas aquí funcionó realmente para mí, resolví el problema con el siguiente código:

button.contentMode = UIViewContentModeScaleToFill; button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill; button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

Puedes hacer esto en el Interface Builder también.


Para Xamarin.iOS (C #):

myButton.VerticalAlignment = UIControlContentVerticalAlignment.Fill; myButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Fill; myButton.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;


Si realmente desea escalar una imagen, hágalo, pero debe redimensionarla antes de usarla. Cambiar el tamaño en tiempo de ejecución simplemente perderá ciclos de CPU.

Esta es la categoría que estoy usando para escalar una imagen:

UIImage + Extra.h

@interface UIImage (Extras) - (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize; @end;

UIImage + Extra.m

@implementation UIImage (Extras) - (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize { UIImage *sourceImage = self; UIImage *newImage = nil; CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (!CGSizeEqualToSize(imageSize, targetSize)) { CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor < heightFactor) scaleFactor = widthFactor; else scaleFactor = heightFactor; scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // center the image if (widthFactor < heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor > heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } // this is actually the interesting part: UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0); CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width = scaledWidth; thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if(newImage == nil) NSLog(@"could not scale image"); return newImage ; } @end

Puedes usarlo al tamaño que quieras. Me gusta :

[self.itemImageButton setImage:[stretchImage imageByScalingProportionallyToSize:CGSizeMake(20,20)]];


Si simplemente quieres reducir la imagen de tu botón:

yourButton.contentMode = UIViewContentModeScaleAspectFit; yourButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);


Tengo un método que lo hace por mí. el método toma uibutton y hace que el aspecto de la imagen se ajuste

-(void)makeImageAspectFitForButton:(UIButton*)button{ button.imageView.contentMode=UIViewContentModeScaleAspectFit; button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill; button.contentVerticalAlignment=UIControlContentVerticalAlignmentFill; }


Tuve problemas con que la imagen no cambiara de tamaño proporcionalmente, por lo que la forma en que lo arreglé fue mediante el uso de bordes.

fooButton.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);


Yo tuve el mismo problema. Simplemente configure el ContentMode de ImageView que se encuentra dentro del UIButton.

[[self.itemImageButton imageView] setContentMode: UIViewContentModeScaleAspectFit]; [self.itemImageButton setImage:[UIImage imageNamed:stretchImage] forState:UIControlStateNormal];

Espero que esto ayude.


asegúrese de haber configurado la imagen en la propiedad de la imagen, pero no en el fondo


Solo necesita establecer el modo de contenido de la vista de imagen UIButton para tres eventos. -

[cell.button setImage:[UIImage imageWithData:data] forState:UIControlStateNormal]; [cell.button setImage:[UIImage imageWithData:data] forState:UIControlStateHighlighted]; [cell.imgIcon setImage:[UIImage imageWithData:data] forState:UIControlStateSelected];

Tenemos código para tres eventos bcoz mientras resaltamos o seleccionamos si el tamaño del botón es CUADRADO y el tamaño de la imagen es rectangular, entonces mostrará una imagen cuadrada en el momento de resaltar o seleccionar.

Estoy seguro de que funcionará para ti.