1. Code
  2. JavaScript

Tip Cepat: Cara Mengubah Ukuran Gambar Secara Otomatis untuk Menyesuaikan Layar

Scroll to top

Indonesian (Bahasa Indonesia) translation by Ari Ana (you can also view the original English article)

Tip Cepat ini menjelaskan cara menggunakan gambar sebagai latar belakang situs web dan mengukurnya secara proporsional dengan ukuran panggung. Ini bagus untuk saat Anda menggunakan SWF yang tinggi-penuh dan lebar-penuh di dalam halaman web.

Ikon iMac oleh bobbyperux.


Pratinjau Hasil Akhir

Lihatlah apa yang akan kita kerjakan. Ubah ukuran jendela browser Anda dan klik SWF untuk mengubah ukuran gambar secara otomatis.


Langkah 1: Membuat File Baru

Mari kita mulai dengan membuat File Actionscript 3.0 yang baru. Simpan sebagai resize.fla di mana pun Anda mau - Saya akan berasumsi C:\resize\resize.fla


Langkah 2: Konfigurasikan Folder-foldernya

Mari kita buat folder yang kita perlukan untuk tutorial ini. Jika Anda sudah familiar dengan classpaths dan Anda memiliki classpath Anda sendiri, buat folder \org\display\ di dalamnya (anggap Anda belum memilikinya dengan nama yang sama).

Jika tidak, buat folder \org\display dalam folder yang sama dengan dokumen resize.fla (misalnya: C:\resize\org\display).


Langkah 3: Impor File Gambar

Impor gambar ke perpustakaan FLA Anda sehingga kita dapat menggunakannya untuk menguji efeknya. Klik File > Import > "Import to library".

Pada dialog yang terbuka, temukan file yang ingin Anda gunakan. Gambar langit yang saya pilih tersedia dalam unduhan Sumber di bagian atas halaman.


Langkah 4: Konfigurasikan Gambar untuk Ekspor

Selanjutnya kita akan mengekspor gambar kita untuk ActionScript, sehingga kita dapat merujuknya dalam kode kita.

Pertama buka perpustakaan Anda (jika Anda tidak dapat melihatnya, klik Window > Library), klik kanan gambar, dan klik Properties.

Ubah namanya menjadi "Sky."

Jika opsi lanjutan tidak terlihat, klik Advanced di sudut kanan bawah jendela Properties. Centang opsinya, "Export for ActionScript" dan "Export in Frame 1", menggunakan nama Sky untuk kelasnya dan flash.display.BitmapData untuk kelas dasar. Juga pastikan opsi "Allow smoothing" dicentang; opsi ini akan memastikan bahwa kita menjaga kualitas gambar yang baik saat mengubah ukuran gambar.

Klik OK untuk menutup panel Properties. Jadi, sekarang kita telah mengkonfigurasi semuanya dalam FLA kita, Anda dapat menyimpannya.


Langkah 5: Kelas Kustom OffsetResize

Sekarang mari kita buat dokumen ActionScript baru dan simpan di dalam folder \org\display\ sebagai OffsetResize.as (misalnya: C:\resize\org\display\OffsetResize.as), atau di dalam folder \org\display\ di classpath Anda.

Selanjutnya: kode. Lihat komentarnya.

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
}

Sekarang Anda dapat menyimpan file OffsetResize.as. Anda dapat menutupnya jika Anda mau; mulai sekarang, kita tidak akan mengeditnya lagi, hanya menggunakannya di dalam kelas lain.


Langkah 6: Konfigurasikan Kelas Dokumen

Sekarang kembali ke FLA dan mari menetapkan kelas dokumen untuk itu. (Tidak akrab dengan kelas dokumen? Baca pengantar singkat ini.)

Buka panel Properties dari FLA dengan cara mengklik di ruang kosong di atas panggung (tanpa objek yang dipilih), kemudian mengklik Window > Properties.

Di panel yang terbuka, ketik "Main" untuk Class (atau Document Class, di Flash CS3).

Simpan FLA lagi tetapi jangan menutupnya.


Langkah 7: Buat Kode Kelas Dokumen

Kita bisa menulis kode kita langsung di timeline, tapi itu bukan kebiasaan yang baik; tujuan dari kelas dokumen adalah untuk menghilangkan pemrograman timeline.

Jadi, buat File ActionScript baru dan simpan sebagai "Main.as" di folder yang sama dengan FLA Anda (misalnya: C:\resize\Main.as).

Mari mengkodenya sekarang (lihat komentar di kode):

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
}

Langkah 8: Uji Coba

Periksa apakah itu baik-baik saja.

  • Kita perlu memiliki gambar di Library yang disebut "Sky" yang diekspor untuk ActionScript dengan nama kelas Sky dan kelas dasar flash.display.BitmapData.
  • Kita juga harus mengatur kelas dokumen ke "Main"
  • file Main.as di folder yang sama dengan FLA
  • dan file OffsetResize.as di dalam \org\display (yang berada di dalam folder yang sama dengan file .fla atau di dalam classpath).

Jika semua persyaratan ini dipenuhi, Anda dapat mengujinya sekarang!

Kesimpulan

Kita membuat kelas kustom yang disebut "OffsetResize", yang mengubah ukuran objek tertentu sesuai dengan ukuran panggung. Jika Anda membuatnya di classpath Anda maka Anda dapat menggunakannya di mana pun Anda mau: semua yang perlu Anda lakukan adalah mengimpor objek OffsetResize dan menggunakannya; itu dapat diperpanjang dan dapat digunakan kembali. Tapi ingat itu untuk digunakan dengan konten terukur, misalnya SWF dalam HTML yang membutuhkan 100% dari lebar dan tinggi.

Terima kasih telah membaca! Posting semua pertanyaan di komentar.