tamaño plus para pantalla medidas fondo color cambio cambiar ios swift xcode background-image

ios - plus - ¿Cómo se hace una escala de imagen de fondo para el tamaño de la pantalla en forma rápida?



mi iphone cambio de color la pantalla (9)

Estoy tratando de hacer una imagen de UIView para mi fondo en forma rápida usando una imagen de patrón. El código que tengo funciona bien, excepto por el hecho de que quiero que la imagen tome toda la pantalla. Mi código se ve así: self.view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)

¿Alguien sabe cómo hacer que el fondo sea una imagen que ocupará toda la pantalla y se escalaría cuando apareciera en diferentes tamaños de pantalla de iPhone?


Simplemente agregue su UIImageView posicionado centrado y con todos los bordes ajustados a los bordes. Déjalo ahí y haga clic en la esquina inferior derecha como se muestra a continuación y ahora continúe y agregue 4 restricciones a los bordes superior, inferior, izquierdo y derecho.

Ahora solo seleccione su vista de imagen y con el inspector de IB seleccione cómo le gustaría su imagen: rellene o ajuste como puede ver de la siguiente manera:


Tenga en cuenta que:

Publiqué esta respuesta de mi cuenta anterior (que está en desuso y no puedo acceder más), esta es mi respuesta mejorada .

Puede hacerlo mediante programación en lugar de crear un IBOutlet en cada vista. simplemente cree una extension UIView (Archivo -> Nuevo -> Archivo -> Archivo Swift -> asígnele el nombre que desee) y agregue:

extension UIView { func addBackground() { // screen width and height: let width = UIScreen.mainScreen().bounds.size.width let height = UIScreen.mainScreen().bounds.size.height let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height)) imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE") // you can change the content mode: imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill self.addSubview(imageViewBackground) self.sendSubviewToBack(imageViewBackground) }}

Ahora puede usar este método con sus vistas, por ejemplo:

override func viewDidLoad() { super.viewDidLoad() self.view.addBackground() }


¡Aquí están sus opciones para escalar!

Para la propiedad .contentMode:

ScaleToFill Esto escalará la imagen dentro de la vista de la imagen para llenar todos los límites de la vista de la imagen.

ScaleAspectFit Esto asegurará que la imagen dentro de la vista de la imagen tenga la relación de aspecto correcta y se ajuste dentro de los límites de la vista de la imagen.

ScaleAspectFill Esto asegurará que la imagen dentro de la vista de la imagen tenga la relación de aspecto correcta y llene todos los límites de la vista de la imagen. Para que este valor funcione correctamente, asegúrese de establecer la propiedad clipsToBounds de la vista de la imagen en verdadero.

class SecondViewController : UIViewController { let backgroundImage = UIImage(named: "centralPark") var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.thirdChoiceField.delegate = self self.datePicker.minimumDate = NSDate() imageView = UIImageView(frame: view.bounds) imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true imageView.image = backgroundImage imageView.center = view.center view.addSubview(imageView) self.view.sendSubviewToBack(imageView)


Esto usa PureLayout . Podrías usar AutoLayout con algunas líneas más.

UIImageView* imgView = UIImageView(image: myUIImage) imgView.setTranslatesAutoresizingMaskIntoConstraints(false) self.view.addSubview(imgView) self.view.addConstraints(imgView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0,0,0,0))


Para esto, creo que necesitarás crear un UIImageView que esté anclado a las vistas padre arriba / abajo / izquierda / derecha. Esto hará que el UIImageView siempre coincida con el tamaño de la pantalla. Solo asegúrate de configurar el modo de contenido en la vista de la imagen para que se ajuste a AspectFit

var newImgThumb : UIImageView newImgThumb = UIImageView(view.bounds) newImgThumb.contentMode = .ScaleAspectFit view.addSubview(newImgThumb) //Don''t forget this line newImgThumb.setTranslatesAutoresizingMaskIntoConstraints(false) NSDictionary *views =NSDictionaryOfVariableBindings(newImgThumb); // imageview fills the width of its superview [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[newImgThumb]|" options:0 metrics:metrics views:views]]; // imageview fills the height of its superview [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[newImgThumb]|" options:0 metrics:metrics views:views]];


Usé restricciones para hacer que la imagen "autoLayout". Hice una vista para mostrar un indicador de actividad (con una imagen de fondo completa), mientras se carga la vista en segue. El código es el siguiente.

var containerView: UIView = UIView() var actionIndicator: UIActivityIndicatorView = UIActivityIndicatorView() private func showActivityIndicator() { ///first I set the containerView and the background image containerView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(containerView) adjustConstFullSize(containerView, parentView: self.view) let backImage = UIImageView(image: UIImage(named: "AppBackImage")) backImage.contentMode = UIViewContentMode.ScaleAspectFill backImage.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(backImage) adjustConstFullSize(backImage, parentView: containerView) ////setting the spinner (activity indicator) actionIndicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0) actionIndicator.center = CGPointMake(containerView.bounds.size.width / 2, containerView.bounds.size.height / 2) actionIndicator.hidesWhenStopped = true actionIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge containerView.insertSubview(actionIndicator, aboveSubview: backImage) ///throw the container to the main view view.addSubview(containerView) actionIndicator.startAnimating() }

Este es el código de la función "adjustConstFullSize".

func adjustConstFullSize(adjustedView: UIView!, parentView: UIView!) { let topConstraint = NSLayoutConstraint(item: adjustedView, attribute: .Top, relatedBy: .Equal, toItem: parentView, attribute: .Top, multiplier: 1.0, constant: 0.0) let leftConstraint = NSLayoutConstraint(item: adjustedView, attribute: .Leading, relatedBy: .Equal, toItem: parentView, attribute: .Leading, multiplier: 1.0, constant: 0.0) let rightConstraint = NSLayoutConstraint(item: adjustedView, attribute: .Trailing, relatedBy: .Equal, toItem: parentView, attribute: .Trailing, multiplier: 1.0, constant: 0.0) let bottomConstraint = NSLayoutConstraint(item: adjustedView, attribute: .Bottom, relatedBy: .Equal, toItem: parentView, attribute: .Bottom, multiplier: 1.0, constant: 0.0) parentView.addConstraints([topConstraint, leftConstraint, rightConstraint, bottomConstraint]) }

En la función que se muestra arriba, "até" las restricciones de containerView a las restricciones de la vista principal, haciendo que la vista sea "de tamaño completo". Hice lo mismo con UIImageView y también configuré el modo de contenido para AspectFill: esto es crucial, porque queremos que la imagen llene el contenido sin extenderse.

Para eliminar la vista, después de la carga diferida, simplemente use el código a continuación.

private func hideActivityIndicator() { actionIndicator.stopAnimating() containerView.removeFromSuperview() }


`

CGRect screenRect = [[UIScreen mainScreen] bounds]; CGFloat screenWidth = screenRect.size.width; CGFloat screenHeight = screenRect.size.height; _imgBackGround.frame = CGRectMake(0, 0, screenWidth, screenHeight);`


Esta es la respuesta actualizada de mi anterior .

Como el mismo enfoque de mi respuesta anterior, puede crear una extensión de UIView y agregarle el método addBackground() , como se addBackground() a continuación:

Recuerde: si lo está agregando en un nuevo archivo .swift, recuerde agregar el import UIKit

extension UIView { func addBackground(imageName: String = "YOUR DEFAULT IMAGE NAME", contentMode: UIViewContentMode = .scaleToFill) { // setup the UIImageView let backgroundImageView = UIImageView(frame: UIScreen.main.bounds) backgroundImageView.image = UIImage(named: imageName) backgroundImageView.contentMode = contentMode backgroundImageView.translatesAutoresizingMaskIntoConstraints = false addSubview(backgroundImageView) sendSubview(toBack: backgroundImageView) // adding NSLayoutConstraints let leadingConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0) let trailingConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0) let topConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0) let bottomConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0) NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint]) } }

Tenga en cuenta que las actualizaciones para esta respuesta son:

  • Código de Swift 3 :)
  • Agregar -programadamente- NSLayoutConstraints : eso se debe a que al aplicar lo mencionado en mi respuesta anterior, funciona bien para la orientación actual del dispositivo, pero no cuando la aplicación admite ambos modos vertical / horizontal, si se ha cambiado la orientación del dispositivo, la imagen de fondo el tamaño será el mismo (el mismo tamaño) y no se adapta al nuevo ancho / alto de la pantalla del dispositivo, por lo que agregar restricciones debería resolver este problema.
  • Agregar parámetros predeterminados: para obtener más flexibilidad, a veces, desee cambiar la imagen predeterminada o incluso el modo de contexto para su fondo:

Uso:

Suponiendo que desea llamarlo en viewDidLoad() :

override func viewDidLoad() { //... // you can call 4 versions of addBackground() method // 1- this will add it with the default imageName and default contextMode view.addBackground() // 2- this will add it with the edited imageName and default contextMode view.addBackground(imageName: "NEW IMAGE NAME") // 3- this will add it with the default imageName and edited contextMode view.addBackground(contentMode: .scaleAspectFit) // 4- this will add it with the default imageName and edited contextMode view.addBackground(imageName: "NEW IMAGE NAME", contextMode: .scaleAspectFit) }


Ahmad Fayyas Solution en Swift 3.0 :

func addBackground() { let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height)) imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE") // you can change the content mode: imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.view.addSubview(imageViewBackground) self.view.sendSubview(toBack: imageViewBackground) }