1. Code
  2. JavaScript

Consejo rápido: cómo cambiar automáticamente el tamaño de una imagen para que se ajuste a la pantalla

Scroll to top

Spanish (Español) translation by steven (you can also view the original English article)

Este consejo rápido explica cómo usar una imagen como fondo de un sitio web y escalarla proporcionalmente al tamaño del escenario. Es ideal para cuando estás utilizando un SWF de altura completa y ancho completo dentro de una página web.

icono de iMac de bobbyperux.


Vista previa del resultado final

Echa un vistazo a lo que vamos a trabajar. Cambia el tamaño de la ventana del navegador y haz clic en el SWF para cambiar automáticamente el tamaño de la imagen.


Paso 1: Crear un nuevo archivo

Comencemos creando un nuevo archivo Actionscript 3.0. Guárdalo como resize.fla donde quieras - Asumiré C:\resize\resize.fla


Paso 2: Configurar las carpetas

Vamos a crear las carpetas que necesitamos para este tutorial. Si estás familiarizado con las rutas de clase y tienes tu propia ruta de clase, crea la carpeta \org\display\ (suponiendo que aún no tengas una con el mismo nombre).

De lo contrario, crea la carpeta \org\display en la misma carpeta que el documento resize.fla (por ejemplo: C:\resize\org\display).


Paso 3: Importar un archivo de imagen

Importa una imagen a tu biblioteca FLA para que podamos usarla para probar el efecto. Haz clic en Archivo > Importar > "Importar a biblioteca".

En el cuadro de diálogo que se abre, busca el archivo que deseas usar. La imagen del cielo que elegí está disponible en los archivos fuente en la parte superior de la página.


Paso 4: Configurar la imagen para exportar

A continuación, exportaremos nuestra imagen para ActionScript, para que podamos referirnos a ella en nuestro código.

Primero abre tu biblioteca (si no puedes verla, haz clic en Ventana > Biblioteca), haz clic con el botón derecho en la imagen y haz clic en Propiedades.

Cambia su nombre a "Sky".

Si las opciones avanzadas no están visibles, haz clic en Avanzadas en la esquina inferior derecha de la ventana Propiedades. Comprueba las opciones "Exportar para ActionScript" y "Exportar en el fotograma 1", utilizando el nombre Sky para la clase y flash.display.BitmapData para la clase base. También asegúrate de que la opción "Permitir suavizado" esté marcada; esta opción asegurará que mantenemos una buena calidad de imagen al cambiar el tamaño de la imagen.

Haz clic en Aceptar para cerrar el panel de Propiedades. Luego, ahora que hemos configurado todo en nuestro FLA, puedes guardarlo.


Paso 5: Clase personalizada OffsetResize

Ahora vamos a crear un nuevo documento de ActionScript y guardarlo dentro de nuestra carpeta \org\display\ como OffsetResize.as (por ejemplo: C:\resize\org\display\OffsetResize.as), o dentro de la carpeta \org\display\ en tu ruta de clase.

Siguiente: código. Echa un vistazo a los comentarios.

1
2
package org.display{
3
	
4
    //Import the needed classes for this object

5
	import flash.display.Sprite;
6
	import flash.display.DisplayObject;
7
	import flash.events.Event;
8
	
9
10
    //Creating a new class extending the Sprite class

11
	public class OffsetResize extends Sprite{
12
		
13
        //Create the static constants for maximum and minimum

14
        //We will use this for the offsetType property

15
		public static const MAX:String="max";
16
		public static const MIN:String="min";
17
18
        //The kind of the resize -- whether the image is bigger or smaller than the stage

19
		private var _offsetType:String;
20
		
21
        //The constructor function

22
		public function OffsetResize($child:DisplayObject,$offsetType:String="max"):void{
23
24
        	//The offsetType; if no value is set the "max" value will be automatically assumed

25
			_offsetType=$offsetType;
26
27
            //Add the child here, any kind of DisplayObject

28
			addChild($child);
29
30
            //Check if this object is on stage. if so, call the init() function

31
			if(stage) init();
32
33
            //If it's not on stage it will listen for when it's added to the stage and then call the init() function

34
			else addEventListener(Event.ADDED_TO_STAGE,init);
35
36
            //This will check when this object is removed from the stage and call the end() function

37
			addEventListener(Event.REMOVED_FROM_STAGE,end);
38
		}
39
		
40
41
        //The init() function (called when the object is in the stage)

42
        //The Event=null parameter is because we used the init() without any parameter in the constructor

43
		// and because it's also used as an event listener (ADDED_TO_STAGE)

44
		private function init(e:Event=null):void{
45
46
        	//Detect when the stage is resized and call the stageResize() function

47
			stage.addEventListener(Event.RESIZE,stageResize);
48
49
            //Call the stageResize() function now, too

50
			stageResize();
51
		}
52
		
53
        //The stageResize() function will be called every time the stage is resized

54
        //The e:Event=null parameter is because we have called the stageResize() function without a parameter

55
		private function stageResize(e:Event=null):void{
56
57
        	//Calculate the width ratio by dividing the stage's width by the object's width

58
			var px:Number=stage.stageWidth/width;
59
60
            //Calculate the height ratio by dividing the stage's height by the object's height

61
			var py:Number=stage.stageHeight/height;
62
63
            /*

64
            	This is the ternary operator; in one line it checks if _offsetType is "max".

65
                If so, it sets the variable div as the maximum value between the width's ratio and the height's ratio.

66
                If not, it sets the variable div as the minimum value between the width's ratio and the height's ratio.

67
                So, this line is responsible for whether the image is bigger or smaller than the stage.

68
            */
69
			var div:Number=_offsetType=="max" ? Math.max(px,py) : Math.min(px,py);
70
71
            //These two lines resize this object according to the division ratio.

72
            //If we use scaleX or scaleY here it wont work as we need it to.

73
			width*=div;
74
			height*=div;
75
76
            //These two lines are responsible for centering this object on the stage.

77
			x=(stage.stageWidth/2)-(width/2);
78
			y=(stage.stageHeight/2)-(height/2);
79
		}
80
		
81
        //This function is called when this object is removed from stage, as we don't need the stageResize() function any more

82
		private function end(e:Event):void{
83
        	//Remove the RESIZE listener from the stage

84
			stage.removeEventListener(Event.RESIZE,stageResize);
85
		}
86
		
87
        /*

88
        	Here we create the offsetType parameter, so we can change how the object

89
            resizes dynamically

90
        */
91
		public function set offsetType(type:String):void{
92
			_offsetType=type;
93
94
            //After changing the type we call stageResize function again to update

95
			if(stage) stageResize();
96
		}
97
		
98
        //Just for if we want to know what the offsetType is

99
		public function get offsetType():String{ return _offsetType; }
100
	}
101
}

Ahora puedes guardar el archivo OffsetResize.as. Puedes cerrarlo si quieres; a partir de ahora, ya no lo editaremos, solo lo usaremos dentro de otras clases.


Paso 6: Configurar la clase documento

Ahora vuelve a la FLA y vamos a asignar una clase de documento a él. (¿No estás familiarizado con las clases documentos? Lee esta introducción rápida.)

Abre el panel Propiedades de la FLA haciendo clic en cualquier espacio en blanco en el escenario (sin objetos seleccionados), luego haz clic en Ventana > Propiedades.

En el panel que se abre, escribe "Main" para la Clase (o para la clase del documento, en Flash CS3).

Guarda el archivo FLA de nuevo, pero no lo cierres.


Paso 7: Código de la clase documento

Podríamos escribir nuestro código directamente en la línea de tiempo, pero ese no es un buen hábito; el propósito de la clase documento es eliminar la programación de la línea de tiempo.

Por lo tanto, crea un nuevo archivo ActionScript y guárdalo como "Main.as" en la misma carpeta que tu FLA (por ejemplo: C:\resize\Main.as).

Codifiquemos ahora (mira los comentarios en el código):

1
2
package{
3
	
4
    //Let's import the needed classes

5
	import org.display.OffsetResize;
6
	import flash.display.Sprite;
7
	import flash.display.Bitmap;
8
	import flash.display.StageAlign;
9
	import flash.display.StageScaleMode;
10
	import flash.events.Event;
11
	import flash.events.MouseEvent;
12
	
13
    //We are extending the Sprite class, rather than MovieClip, since we won't use any timeline animation here

14
	public class Main extends Sprite{
15
		
16
        //This will be the instance of our custom object OffsetResize

17
		private var _bg:OffsetResize;
18
		
19
        //The constructor

20
		public function Main():void{
21
22
        	/*

23
            	We could use the stage property directly here, but I'm assuming that a lot of people

24
                create a document like "base.swf" which loads the "main.swf" file -- in which case our

25
                main.swf wouldn't have the stage property.

26
				

27
                But it checks if there is a stage property. We can use this swf we will create with

28
                or without the base.swf; in this case we will use it without the base.swf, but it's

29
                prepared to use with the latter if we want.

30


31
                So this line will check if our swf is on the stage, and, if so, call init().

32
            */
33
			if(stage) init();
34
35
            //If not on the stage it will call the init() function only when it's added to the stage

36
			else addEventListener(Event.ADDED_TO_STAGE,init);
37
		}
38
		
39
        //The init function is called only when the object is in the stage

40
        //It was explained before whe we are using this in the constructor function

41
		private function init(e:Event=null):void{
42
43
        	//Setting how the stage will scale (it will not scale) and its alignment (top-left corner)

44
			stage.scaleMode=StageScaleMode.NO_SCALE;
45
			stage.align=StageAlign.TOP_LEFT;
46
47
            //Remember the picture in the library? Well, this is why we exported it for AS.

48
            //Let's create a Bitmap object with that image:

49
			var picture:Bitmap=new Bitmap(new Sky(0,0));
50
51
            //Now we create an instance of the OffsetResize class we coded before.

52
            //The second parameter is optional and can be left blank; its value can be OffsetResize.MAX or OffsetResize.MIN.

53
			_bg=new OffsetResize(picture,OffsetResize.MIN);
54
55
            //add the instance of the OffsetResize to the stage at child index 0, so it will be behind everything (it's a background)

56
			stage.addChildAt(_bg,0);
57
58
            //The code so far is enough to make this work, but I will show how to change the offsetType dynamically.

59
            //So let's add a MOUSE_DOWN event, which will call the mouseDown() function when we click on the stage.

60
			stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDown);
61
		}
62
		
63
        //This function is called every time that we click the stage

64
		private function mouseDown(e:MouseEvent):void{
65
        	/*

66
            	This is the ternary operator, it's a compact version of this long if statement:

67
                if(_bg.offsetType==OffsetResize.MAX){

68
                	_bg.offsetType=OffsetResize.MIN;

69
                }

70
                else{

71
                	_bg.offsetType=OffsetResize.MAX;

72
                }

73
            */
74
			_bg.offsetType = _bg.offsetType==OffsetResize.MAX ? OffsetResize.MIN : OffsetResize.MAX;
75
		}
76
	}
77
}

Paso 8: Pruébalo

Comprueba si está bien.

  • Necesitamos tener una imagen en la Biblioteca llamada "Sky" que se exporta para ActionScript con un nombre de clase Sky y una clase base de flash.display.BitmapData.
  • También debemos tener la clase del documento establecida en "Main"
  • el archivo Main.as en la misma carpeta que el archivo FLA
  • y el archivo OffsetResize.as dentro de \org\display (que está dentro de la misma carpeta que el archivo .fla o está dentro de la ruta de clase).

Si se cumplen todos estos requisitos, ¡puedes probarlo ahora!

Conclusión

Creamos una clase personalizada llamada "OffsetResize", que cambia el tamaño de un objeto especificado de acuerdo con el tamaño de la etapa. Si lo creaste en tu ruta de clase, puedes usarlo donde lo desees: todo lo que necesitas hacer es importar el objeto OffsetResize y usarlo; es extensible y reutilizable. Pero recuerda que se debe utilizar con contenido escalable, por ejemplo, un SWF en HTML que ocupa el 100% del ancho y alto.

¡Gracias por leer! Publica cualquier pregunta en los comentarios.