as3 Full Background Image Class


/ Published in: ActionScript 3
Save to your folder(s)

Full Background class with min. width and height


Copy this code and paste it in your HTML
  1. package com.jasonhulbert.display{
  2. import flash.events.Event;
  3. import flash.display.Sprite;
  4. import flash.display.Bitmap;
  5. import flash.display.Loader;
  6. import flash.net.URLRequest;
  7. import flash.errors.IOError;
  8. import flash.events.IOErrorEvent;
  9. import flash.display.StageScaleMode;
  10. import flash.display.StageAlign;
  11.  
  12. public class FullBackground extends Sprite {
  13.  
  14. var ldr:Loader;
  15. var ldrReq:URLRequest;
  16. var bmp:Bitmap;
  17.  
  18. var minW:Number;
  19. var minH:Number;
  20.  
  21. var stageW:Number;
  22. var stageH:Number;
  23. var scaler:Number;
  24.  
  25. public function FullBackground(_imageURL:String, _minW:Number, _minH:Number) {
  26. minW = _minW;
  27. minH = _minH;
  28.  
  29. ldr = new Loader ;
  30. ldrReq = new URLRequest(_imageURL);
  31. ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
  32. ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
  33. addEventListener(Event.ADDED_TO_STAGE, onAdd);
  34. }
  35.  
  36. private function onAdd(event:Event):void {
  37. stage.scaleMode = StageScaleMode.NO_SCALE;
  38. stage.align = StageAlign.TOP_LEFT;
  39. stage.addEventListener(Event.RESIZE, onStageResize);
  40. ldr.load(ldrReq);
  41. }
  42.  
  43. private function onLoaded(event:Event):void {
  44. bmp = Bitmap(ldr.content);
  45. bmp.smoothing = true;
  46. addChild(bmp);
  47.  
  48. resizeImage();
  49. }
  50.  
  51. private function onIOError(event:IOErrorEvent):void {
  52. trace("Error loading background image: " + event);
  53. }
  54.  
  55. private function resizeImage():void {
  56. stageW = stage.stageWidth;
  57. stageH = stage.stageHeight;
  58.  
  59. if (stageH / stageW > this.height / this.width) {
  60. scaler = this.width / this.height;
  61. this.width = stageH * scaler;
  62. this.height = stageH;
  63. } else {
  64. scaler = this.height / this.width;
  65. this.height = stageW * scaler;
  66. this.width = stageW;
  67. }
  68. this.x = (stageW / 2) - (this.width / 2);
  69. this.y = 0;
  70. }
  71.  
  72. private function onStageResize(event:Event):void {
  73. resizeImage();
  74. }
  75.  
  76. }
  77.  
  78. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.