Loading an external swf - dimensions not correct - actionscript-3

I have a main swf file. It has a simple empty movieclip with instance name mc_external_swf.
Now I use the document class to load an external swf file. The external file loads and is visible, but its dimensions are not fitting inside the movieclip conatiner, some of the stuff from the external swf is overlapping outside of the movieclip container. Look in the image below.
Here is the code used to load the external swf file.
var _swfLoader:Loader;
var _swfContent:MovieClip;
function goToPlay(e:MouseEvent=null):void
{
loadSWF("agameFLA.swf");
}
public function loadSWF(path:String):void
{
var _req:URLRequest = new URLRequest();
_req.url = path;
_swfLoader = new Loader();
setupListeners(_swfLoader.contentLoaderInfo);
_swfLoader.load(_req);
}
function setupListeners(dispatcher:IEventDispatcher):void
{
dispatcher.addEventListener(Event.COMPLETE, addSWF);
}
function addSWF(event:Event):void
{
event.target.removeEventListener(Event.COMPLETE, addSWF);
event.target.removeEventListener(ProgressEvent.PROGRESS, preloadSWF);
_swfContent = event.target.content;
mc_external_swf.addChild(_swfContent);
}
Here is the code of the External File itself - (Of its Document Class)
package
{
import away3d.cameras.Camera3D;
import away3d.cameras.lenses.PerspectiveLens;
import away3d.containers.ObjectContainer3D;
import away3d.containers.Scene3D;
import away3d.containers.View3D;
import away3d.controllers.HoverController;
import away3d.entities.Mesh;
import away3d.materials.ColorMaterial;
import away3d.primitives.CubeGeometry;
import flash.display.MovieClip;
public class Main extends MovieClip
{
public var _view : View3D;
private var _scene:Scene3D;
private var _camera : Camera3D;
private var _hoverController:HoverController;
private var _container:ObjectContainer3D;
private var _cube:CubeGeometry;
private var _cubeMaterial:ColorMaterial;
private var _cubeMesh:Mesh;
public function Main()
{
addEventListener(Event.ADDED_TO_STAGE,init);
}
private function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE,init);
iniScene();
iniObjects();
}
private function iniScene():void
{
_scene = new Scene3D();
_view = new View3D();
_view.backgroundColor = 0x666666;
_view.antiAlias = 4;
_camera= new Camera3D();
_camera.lens = new PerspectiveLens(60);
_hoverController = new HoverController(_camera, null, 180, 0);
_hoverController.distance = 400;
_hoverController.steps = 16;
_view.camera = _camera;
this.addChild(_view);
}
private function iniObjects():void
{
_container = new ObjectContainer3D();
_cube = new CubeGeometry(100, 100, 100, 20, 20, 20);
_cubeMaterial = new ColorMaterial(0x0000FF);
_cubeMesh = new Mesh(_cube, _cubeMaterial);
_cubeMesh.mouseEnabled = true;
_container.addChild(_cubeMesh);
_view.scene.addChild(_container);
this.addEventListener(Event.ENTER_FRAME, _onEnterFrame);
_onResize();
}
private function _onResize(e:Event=null):void
{
_view.width = stage.stageWidth;
_view.height = stage.stageHeight;
}
private function _onEnterFrame(e:Event):void
{
_view.render();
}
}
}
It might be happening to the away3d library. I have tried to load other swfs but they fit in well. But this swf in particular does not fit in the movieclip container. I think it has got something to do with view3d in away3d but I am not sure.

All the tutorials on Stage3D (or libraries such as Away3D) that i have seen have included the following code in the main class:
public function Main()
{
//wait until stage object is ready
addEventListener(Event.ADDED_TO_STAGE, addedHandler);
}
private function addedHandler(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, addedHandler);
stage.align = "TL"; //or use StageAlign.TOP_LEFT;
stage.scaleMode = "noScale"; //or use StageScaleMode.NO_SCALE;
}
It will stop the swf from scaling.

Related

Adding EventListener to Sprites in other classes does not work in AS3

I have my main class where I add EventLisitener to Sprites in other classes Like so:
public function Main() {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
addChild(Menu.menuBackground);
addChild(Menu.startButton);
//Adds event Listener to Menu's Sprite startButton.
Menu.startButton.addEventListener(MouseEvent.CLICK, startGame);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
}
This all works Fine and Dandy but later I try to do it again, the same way. But, clicking on the sprites does nothing. Here is the full Main Class code. Along with the code for the other three Sprite classes.
Full Main:
package {
//Other Files
import Menu;
import CrossHair;
import Birds;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public class Main extends Sprite {
//Game values
public static var gameWidth:int = 750;
public static var gameHeight:int = 750;
[Embed (source = "lib/background.png")]
public var backgroundClass:Class;
public var background:Bitmap = new backgroundClass();
public function Main() {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
addChild(Menu.menuBackground);
addChild(Menu.startButton);
Menu.startButton.addEventListener(MouseEvent.CLICK, startGame);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
}
//Function starts game
public function startGame(Evt:Event):void {
Mouse.hide(); //Hides Mouse
removeChild(Menu.startButton); //Get rid of startButton
Menu.startButton.removeEventListener(MouseEvent.CLICK, startGame);
reRender();
//Add eventListiners
addEventListener(Event.ENTER_FRAME, update);
Birds.bird.addEventListener(MouseEvent.CLICK, Birds.shot);
EnterShopButton.shopButton.addEventListener(MouseEvent.CLICK, enterShop);
}
public function reRender():void {
addChild(background); //Add background
addChild(Birds.bird); //Add birds.
addChild(EnterShopButton.shopButton); //Add UpgradeMenuButton
addChild(CrossHair.crossHair); //Add crosshair
}
public function enterShop():void {
stage.removeChildren(); //Removes all children from stage.
}
public function update(evt:Event):void {
Birds.update();
CrossHair.crossHair.x = mouseX - (CrossHair.crossHairImg.width / 2);
CrossHair.crossHair.y = mouseY - (CrossHair.crossHairImg.height / 2);
}
}
}
Event Lisitners:
package {
//Other files
import flash.events.Event;
import Main;
import flash.display.Sprite;
import flash.display.Bitmap;
public class Menu extends Sprite {
//create menbu background Bitmap
[Embed (source = "lib/menubackground.png")]
public static var menuBackgroundClass:Class;
public static var menuBackground:Bitmap = new menuBackgroundClass();
//create startButton Bitmap
[Embed (source = "lib/menustartbutton.png")]
public static var startButtonClass:Class;
public static var startButtonImg:Bitmap = new startButtonClass();
public static var startButton:Sprite = new Sprite();
//Set startButton's values
startButton.addChild(startButtonImg);
startButton.x = (Main.gameWidth / 2) - (startButtonImg.width / 2);
startButton.y = (Main.gameHeight / 2) - (startButtonImg.height / 2);
}
}
package {
//Other files
import Main;
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.events.MouseEvent;
public class Birds extends Sprite {
public static var xSpeed:int = 10;
public static var ySpeed:int = 10;
public static var dead:Boolean = false;
//Create bird Sprite
[Embed (source = "lib/bird.png")]
public static var birdClass:Class;
[Embed (source = "lib/birdead.png")]
public static var deadBirdClass:Class;
public static var birdImg:Bitmap = new birdClass();
public static var deadBirdImg:Bitmap = new deadBirdClass();
public static var bird:Sprite = new Sprite();
//Sets Sprite's values
bird.addChild(birdImg);
bird.buttonMode = true;
bird.x = 0;
bird.y = 0;
public static function update():void {
bird.x += Math.random() * xSpeed;
bird.y += Math.random() * ySpeed;
if (!dead) {
if (bird.x >= (Main.gameWidth - birdImg.width) || bird.x <= 0) {
xSpeed = xSpeed * -1;
}
if (bird.y >= (Main.gameHeight - birdImg.height) || bird.y <= 0) {
ySpeed = ySpeed * -1;
}
} else {
if (bird.y > (Main.gameHeight - deadBirdImg.height)) {
resetBird();
}
}
}
public static function shot(evt:MouseEvent):void {
if (!dead) {
bird.removeChild(birdImg);
bird.addChild(deadBirdImg);
dead = true;
xSpeed = 0;
ySpeed = 50;
}
}
public static function resetBird():void {
bird.removeChild(deadBirdImg);
bird.addChild(birdImg);
dead = false;
bird.x = 0
bird.y = 0;
xSpeed = 10;
ySpeed = 10;
}
}
}
package {
//Other Files
import Main;
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.events.Event;
import flash.events.MouseEvent;
public class EnterShopButton extends Sprite{
//Create crossHair
[Embed (source = "lib/shopbutton.png")]
public static var shopButtonClass:Class;
public static var shopButtonImg:Bitmap = new shopButtonClass();
public static var shopButton:Sprite = new Sprite();
//Set CrossHair's values
shopButton.addChild(shopButtonImg);
shopButton.buttonMode = true;
shopButton.x = Main.gameWidth - shopButtonImg.width;
shopButton.y = Main.gameHeight - shopButtonImg.height;
}
}
Same problem, same answer. Your previous question was answered the same way but you still persist on doing the exact same thing and getting into the exact same problem.
Stop trying to run code in static scope! addChild can't work in that scope and any other type of code.
Not sure why I was voted down. There's not much to answer here since the same problem with the same user was answered in another post.
This is really not difficult, user wants to run code at class definition scope. At class definition scope you can instantiate variable yes but that's all you can do. User wants to run code and logic at that scope and this is just completely ignored by the compiler. This was already pointed out to him in his previous question and he was even given the advice to stop trying to run code at that scope to avoid further problem. This is really simple to understand:
[Embed (source = "lib/menubackground.png")]
public static var menuBackgroundClass:Class;
public static var menuBackground:Bitmap = new menuBackgroundClass();
//instantiation is allowed at that scope and will work
//create startButton Bitmap
[Embed (source = "lib/menustartbutton.png")]
public static var startButtonClass:Class;
public static var startButtonImg:Bitmap = new startButtonClass();
//instantiation is allowed at that scope and will work
public static var startButton:Sprite = new Sprite();
//instantiation is allowed at that scope and will work
//COMPILER WILL IGNORE AT THAT SCOPE ANY CODE THAT IS NOT INSTANTIATION
//SO ALL FOLLOWING LINES ARE IGNORED AND PRODUCE NO RESULT
//EVEN TRACING WOULD NOT WORK HERE
// (Main.gameWidth / 2) WILL NOT BE CALCULATED AND DOES NOT PRODUCE ANY VALUE
// startButton.x WILL NOT BE SET AND WILL STAY AT DEFAULT VALUE 0
// FINALLY startButton WILL NOT addChild ANYTHING.
//ANY FORM OF CODE LOGIC IS IGNORED AT THAT SCOPE AND WILL NEVER PRODUCE ANY RESULT
startButton.addChild(startButtonImg);
startButton.x = (Main.gameWidth / 2) - (startButtonImg.width / 2);
startButton.y = (Main.gameHeight / 2) - (startButtonImg.height / 2);

Correct usage of addtoStage when loading external swf

I am loading an external swf file into a parent swf file.
Previously, I was getting error 1009 and fixed that by using a listener event to add the swf to the stage before running any scripts.
The swf however fails to load completely when embedded into a parent swf as seen in this URL
http://viewer.zmags.com/publication/06b68a69?viewType=pubPreview#/06b68a69/1
Here is the code I am using.
Thank you for any input.
package
{
import com.greensock.TweenLite;
import flash.display.DisplayObject;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.SpreadMethod;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class slider5 extends Sprite
{
public var thumbPath:String = "Trailchair_thumb";
public var featPath:String = "Trailchair";
public var sliderIndex:Number = 1;
public var currBg:Bitmap = new Bitmap();
public var thumbCount:Number = 8;
public var thumbHolder:Sprite = new Sprite();
public var thumbMask:Sprite = new Sprite();
public var thumbX:Number = 0;
public var thmPadding:Number = 10;
public var thmWidth:Number;
public var navLeft:Sprite = new Sprite();
public var navRight:Sprite = new Sprite();
public var timer:Timer = new Timer(5000,0);
public var sliderDir:String = "fwd";
public function slider5()
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function onAddedToStage(e:Event):void{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
//THE BACKGROUND IMAGE
currBg.alpha = 1;
stage.addChildAt(currBg, 0);
changeBg(sliderIndex);
//The thumbMask a sprite with graphic rectangle
thumbMask.x = 87;
thumbMask.y = 572;
thumbMask.graphics.beginFill(0xFFFFFF);
thumbMask.graphics.drawRect(0,0, 406, 181);
stage.addChildAt(thumbMask, 2);
//The thumbSlider
thumbHolder.x = 228;
thumbHolder.y = 573;
stage.addChildAt(thumbHolder, 1);
thumbHolder.mask = thumbMask;
buildThumbs();
//add the nav
navLeft.x = 100;
navLeft.y = 609;
navRight.x = 496;
navRight.y = 609;
stage.addChildAt(navLeft, 4);
stage.addChildAt(navRight, 4);
var navBmp:Bitmap = new Bitmap();
navBmp.bitmapData = new navarrow(109,109);
var navBmp_Rt:Bitmap = new Bitmap();
navBmp_Rt.bitmapData = new navarrow(109,109);
navLeft.addChild(navBmp);
navLeft.scaleX *= -1;
navRight.addChild(navBmp_Rt);
navLeft.useHandCursor = true;
navLeft.buttonMode = true;
navRight.useHandCursor = true;
navRight.buttonMode = true;
navLeft.name = "left";
navRight.name = "right";
navLeft.addEventListener(MouseEvent.CLICK, navClick);
navRight.addEventListener(MouseEvent.CLICK, navClick);
//add the active item frame
var frame:Sprite = new Sprite();
frame.x = 226;
frame.y = 570;
frame.graphics.lineStyle(10, 0x000000);
frame.graphics.drawRect(0,0,131, 181);
stage.addChildAt(frame, 6);
timer.addEventListener(TimerEvent.TIMER, timeEvt);
timer.start();
}
public function changeBg(index):void
{
//set the first slide from our library and add to the stage
var currBg_Class:Class = getDefinitionByName( featPath + index ) as Class;
currBg.bitmapData = new currBg_Class(597,842);
//fade it in
TweenLite.from(currBg, 0.5, {alpha:0});
}
public function buildThumbs():void
{
var currThm:Class;
for (var i:uint = 1; i<=thumbCount; i++)
{
currThm = getDefinitionByName( thumbPath + i ) as Class;
var thmBmp:Bitmap = new Bitmap();
thmBmp.bitmapData = new currThm(126,176);
thmBmp.x = thumbX;
thumbHolder.addChild(thmBmp);
thumbX += thmBmp.width + thmPadding;
}
thmWidth = thmBmp.width + thmPadding;
}
public function navClick(e):void
{
timer.reset();
timer.start();
var dir:String = e.currentTarget.name;
if (dir=="left" && thumbHolder.x < 228 )
{
sliderIndex--;
TweenLite.to(thumbHolder, 0.5, {x:thumbHolder.x + thmWidth});
//thumbHolder.x = thumbHolder.x + thmWidth;
}
else if (dir=="right" && thumbHolder.x > - 724 )
{
sliderIndex++;
TweenLite.to(thumbHolder, 0.5, {x:thumbHolder.x - thmWidth});
//thumbHolder.x = thumbHolder.x - thmWidth;
}
if (sliderIndex == thumbCount)
{
sliderDir = "bk";
}
if (sliderIndex == 1)
{
sliderDir = "fwd";
}
changeBg(sliderIndex);
}
public function timeEvt(e):void
{
if (sliderDir == "fwd")
{
navRight.dispatchEvent(new Event(MouseEvent.CLICK));
}
else if (sliderDir == "bk")
{
navLeft.dispatchEvent(new Event(MouseEvent.CLICK));
}
}
}
}
If you still need it you can try these two suggestions. Note I didnt know about Zmags and initially assumed that it was your own domain name. That's why I suggested you use the Loader class. It worked for me when I did a test version of a parent.swf' that loaded a test 'child.swf' containing your code. It actually loaded the child swf without problems.
Change from extending Sprite to extending MovieClip
Avoid checking for added to stage in this project
Explanations:
Extending MovieClip instead of Sprite
I Long story short Flash wont like your swf extending Sprite then being opened by a parent loader that extends Movieclip. The ZMag player will be extending MovieClip. It's logical and the docs do confirm this in a way. Whether it fixes your issue or not just keep it MovieClip when using ZMags.
Avoiding Stage referencing in your code..
Looking at this Zmags Q&A documentaion:
http://community.zmags.com/articles/Knowledgebase/Common-questions-on-flash-integration
Looking at Question 4.. In their answer these two stand out.
Reference of the stage parameter in the uploaded SWF conflicting with the publication
Badly or locally referenced resources in the SWF you uploaded which cannot be found
Is it really necessary to have an added_to_stage check in this? If it wont hurt then I suggest dropping the stage_added checking from function slider5() and instead cut/paste in there the code you have from the function onAddedToStage(e:Event).
Hope it helps.

away3d and cs6 external as3 file

i need some help to lunch external action script file lets say i have this file :
Basic_SkyBox.as
and this the code for it :
package
{
import away3d.cameras.lenses.*;
import away3d.containers.*;
import away3d.entities.*;
import away3d.materials.*;
import away3d.materials.methods.*;
import away3d.primitives.*;
import away3d.textures.*;
import away3d.utils.*;
import flash.display.*;
import flash.events.*;
import flash.geom.Vector3D;
[SWF(backgroundColor="#000000", frameRate="60", quality="LOW")]
public class Basic_SkyBox extends Sprite
{
// Environment map.
[Embed(source="../embeds/skybox/snow_positive_x.jpg")]
private var EnvPosX:Class;
[Embed(source="../embeds/skybox/snow_positive_y.jpg")]
private var EnvPosY:Class;
[Embed(source="../embeds/skybox/snow_positive_z.jpg")]
private var EnvPosZ:Class;
[Embed(source="../embeds/skybox/snow_negative_x.jpg")]
private var EnvNegX:Class;
[Embed(source="../embeds/skybox/snow_negative_y.jpg")]
private var EnvNegY:Class;
[Embed(source="../embeds/skybox/snow_negative_z.jpg")]
private var EnvNegZ:Class;
//engine variables
private var _view:View3D;
//scene objects
private var _skyBox:SkyBox;
private var _torus:Mesh;
/**
* Constructor
*/
public function Basic_SkyBox()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
//setup the view
_view = new View3D();
addChild(_view);
//setup the camera
_view.camera.z = -600;
_view.camera.y = 0;
_view.camera.lookAt(new Vector3D());
_view.camera.lens = new PerspectiveLens(90);
//setup the cube texture
var cubeTexture:BitmapCubeTexture = new BitmapCubeTexture(Cast.bitmapData(EnvPosX), Cast.bitmapData(EnvNegX), Cast.bitmapData(EnvPosY), Cast.bitmapData(EnvNegY), Cast.bitmapData(EnvPosZ), Cast.bitmapData(EnvNegZ));
//setup the environment map material
var material:ColorMaterial = new ColorMaterial(0xFFFFFF, 1);
material.specular = 0.5;
material.ambient = 0.25;
material.ambientColor = 0x111199;
material.ambient = 1;
material.addMethod(new EnvMapMethod(cubeTexture, 1));
//setup the scene
_torus = new Mesh(new TorusGeometry(150, 60, 40, 20), material);
_view.scene.addChild(_torus);
_skyBox = new SkyBox(cubeTexture);
_view.scene.addChild(_skyBox);
//setup the render loop
addEventListener(Event.ENTER_FRAME, _onEnterFrame);
stage.addEventListener(Event.RESIZE, onResize);
onResize();
}
/**
* render loop
*/
private function _onEnterFrame(e:Event):void
{
_torus.rotationX += 2;
_torus.rotationY += 1;
_view.camera.position = new Vector3D();
_view.camera.rotationY += 0.5*(stage.mouseX-stage.stageWidth/2)/800;
_view.camera.moveBackward(600);
_view.render();
}
/**
* stage listener for resize events
*/
private function onResize(event:Event = null):void
{
_view.width = stage.stageWidth;
_view.height = stage.stageHeight;
}
}
}
ok then i create new action script page how i can refer the above file script to run in main page of projects in flash cs6 ??
You need to set the Document Class to Basic_Skybox. Make sure the .fla and Basic_Skybox.as are in the same directory.
Here's a tutorial on doing so: http://active.tutsplus.com/tutorials/actionscript/quick-tip-how-to-use-a-document-class-in-flash/

flash as3 trying to play audio from external swf and getting message "Call to a possibly undefined method"

I'm able to load graphics from an external library with no problems, but for some reason all of the audio will not load/play.
Here's the loader class I'm using...
package
{
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.events.Event;
import flash.net.URLRequest;
import flash.text.Font;
public class LoadLibrary extends MovieClip
{
private var gear:MovieClip = new mcGear();
private var txtLoading:BlankClip;
private var _gameLib:String = "";
private var _Impact:Font = new Impact();
public function LoadLibrary(gameLibrary:String)
{
_gameLib = gameLibrary;
addChild(gear);
gear.x = 512;
gear.y = 384;
gear.alpha = .2;
gear.scaleX = .33;
gear.scaleY = .33;
txtLoading = new BlankClip(_Impact, "LOADING...", -400, -60, 800, 120, 26, "center", 5);
addChild(txtLoading);
txtLoading.x = 512;
txtLoading.y = 525;
txtLoading.alpha = .2;
var request:URLRequest = new URLRequest(_gameLib);
LoadVars.LIBLOADER.contentLoaderInfo.addEventListener(Event.COMPLETE, gameLibraryLoaded);
LoadVars.LIBLOADER.load(request);
}
private function gameLibraryLoaded(e:Event):void
{
removeChild(gear);
removeChild(txtLoading);
LoadVars.LIBLOADER.contentLoaderInfo.removeEventListener(Event.COMPLETE, gameLibraryLoaded);
var loaderInfo:LoaderInfo = LoaderInfo(e.currentTarget);
LoadVars.APPDOMAIN = loaderInfo.applicationDomain;
dispatchEvent(new GameEvents(GameEvents.LIBRARY_LOADED));
}
}
}
and the functions in my main class...
private function loadLib():void
{
_loadGraphics = new LoadLibrary("Elemental_Library.swf");
addChild(_loadGraphics);
_loadGraphics.addEventListener(GameEvents.LIBRARY_LOADED, test);
}
private function test(e:GameEvents):void
{
trace("LOADED");
var music:Sound = new GameMusic();
music.play();
}
Everything works fine until I try music.play and I get "1180: Call to a possibly undefined method GameMusic." I've tried several other audio clips and I get the same message. I tried creating a new library and imported just one audio file, same message. I verified I'm using the correct linkage names and the crazy part is that all of the movie clips load just fine from the same library.
Changed test to...
private function test(e:GameEvents):void
{
trace("LOADED");
var musicClass:Class = Class(LoadVars.APPDOMAIN.getDefinition("GameMusic"));
var music:Sound = Sound(new musicClass()); music.play();
}
I knew it was something stupid :P

How to merge two bitmaps into one bitmap and save it to local drive

I've searched a lot but nothing seems working for me. Assistance of somebody is very much appreciated in this regard. Thanks a lot. I'm new to AS3. I'm using FlashDevelop. Below is the code I used,
package
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BitmapDataChannel;
import flash.net.URLRequest;
import flash.events.MouseEvent;
import flash.utils.ByteArray;
import flash.net.FileReference;
import com.adobe.images.JPGEncoder;
import flash.geom.Rectangle;
public class Main extends Sprite
{
private var modelBmp : BitmapData;
private var alphaBmp : BitmapData;
private var destPoint : Point = new Point(0, 0);
private var mask1:Loader = new Loader();
private var mask2:Loader = new Loader();
private var f:Bitmap;
private var fileReference:FileReference = new FileReference();
private var movie:MovieClip = new MovieClip();
private var loadedimage:Bitmap;
private var loadedimage1:Bitmap;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
if (loadAssets()) {
trace('merge loaded');
modelBmp = new BitmapData(loadedimage.width, loadedimage.height);
modelBmp.draw(loadedimage);
alphaBmp = new BitmapData(loadedimage1.width, loadedimage1.height);
alphaBmp.draw(loadedimage1);
var rect:Rectangle = new Rectangle(0, 0, 200, 200);
var pt:Point = new Point(20, 20);
var mult:uint = 0x80; // 50%
modelBmp.merge(alphaBmp, rect, pt, mult, mult, mult, mult);
var bm1:Bitmap = new Bitmap(modelBmp);
addChild(bm1);
bm1.x = 400;
var bm2:Bitmap = new Bitmap(alphaBmp);
addChild(bm2);
bm2.x = 200;}
}
private function loadAssets():void
{
mask2.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete1);
mask1.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
mask2.load(new URLRequest("Photo.png"));
mask1.load(new URLRequest("back.png"));
trace('asset loaded');
}
private function loadComplete(event:Event):void
{
loadedimage = Bitmap(mask1.content)
var bitmap:BitmapData = new BitmapData(loadedimage.width, loadedimage.height, false, 0xffffffff);
bitmap.draw(loadedimage, new Matrix())
var image:Bitmap = new Bitmap(bitmap);
//addChild(image);
trace('image1 loaded');
}
private function loadComplete1(event:Event):void
{
loadedimage1 = Bitmap(mask2.content)
var bitmap:BitmapData = new BitmapData(loadedimage1.width, loadedimage1.height, false, 0xffffffff);
bitmap.draw(loadedimage1, new Matrix())
var image:Bitmap = new Bitmap(bitmap);
//addChild(image);
trace('image2 loaded');
}
}
}
How to use Bitmap.merge():
var bitMapData1:BitmapData = new BitmapData(100,100); //or embedded item
var bitMapData2:BitmapData = new BitmapData(100,100); // "
var bitmap:Bitmap = new Bitmap(bitMapData1);
this.addChild(bitmap);
bitmap.merge(bitMapData2, new Rectangle(0, 0, 100, 100), new Point(0, 0), 128, 128, 128, 128);
As others have noted, Flash is forbidden from creating, altering, modifying, saving or otherwise manipulating files. There are several ways of getting this data out of flash and into a technology that has these abilities (such as PHP), or you can use the flash.filesystem package in Air (as previously noted).
Hope that helps =
= update =
Your code is problematic in that you are writing your urlRequest and then acting upon the loaded content in one function. The URL request simply hasn't had time to fire, and the rest of your function fails, because Mask2.content == undefined or null... I'm surprised it doesn't throw an error.
Other than that, it looks like it should work.
Try this:
private var _mask1:Loader; // _lowerCase naming convention
//constructor... call init()
//init.. call loadAssets()
private function loadAssets():void
{
_mask1 = new Loader(); //generally not a good idea to create objects when declaring variable
_mask1.addEventListener(Event.COMPLETE, onCompleteFunction);
_mask1.load(new URLRequest("Dress04.png"));
private function onCompleteFunction(e:Event):void
{ ...
Note that since you are doing multiple loads, you will need to check if both are loaded before acting upon the loaded content. You can do this with a simple boolean check or... whatever. You might also check out something like LoaderMax, which has built in load queueing like this.
Note also that good asset loading usually involves a try...catch statement and the handling of several events - IOErrorEvent.IO_ERROR , for example.
= update 2 =
Okay - we're just getting into programming logic now.
This is a problem:
private function init(e:Event = null):void
{
if (loadAssets()) {
trace('merge loaded');
//...
//...
private function loadAssets():void
{...
You're essentially asking loadAssets() to a return a value, but its return type is void, and so will absolutely fail. Besides that, the loadAssets() is only instigating the loader, and not tracking whether the load was successful.
Lets break it into a few more steps, and set up a really simple loading queue:
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.URLRequest;
public class Main extends Sprite
{
private var modelBmp : BitmapData;
private var alphaBmp : BitmapData;
private var destPoint : Point;
private var mask : Loader;
private var f : Bitmap;
private var movie : MovieClip;
private var loadedImages: Array;
private var imageQueue : Array;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
//initialize variables
private function init(e:Event = null):void
{
//just set up a simple queue of images to load
imageQueue = ['Photo.png', 'back.png'];
loadedImages = [];
destPoint = new Point(0, 0);
mask = new Loader();
movie = new MovieClip();
loadAsset( imageQueue[0] );
}
private function loadAsset(target:String):void
{
mask.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
mask.load(new URLRequest(target));
}
private function loadComplete(event:Event):void
{
loadedimage = Bitmap(mask.content);
var bitmap:BitmapData = new BitmapData(loadedimage.width, loadedimage.height, false, 0xffffffff);
bitmap.draw(loadedimage, new Matrix())
var image:Bitmap = new Bitmap(bitmap);
loadedImages.push(image);
mask.unload();
trace(imageQueue[0] + " loaded");
imageQueue.splice( 0, 1); //remove the first index
if (imageQueue.length > 0){
loadAsset(imageQueue[0]);
}else{
mergeImages(); //if the queue is empty, then merge
}
}
private function mergeImages():void
{
modelBmp = new BitmapData(Bitmap(loadedImages[0]).width, Bitmap(loadedImages[0]).height);
modelBmp.draw(loadedimage);
alphaBmp = new BitmapData(Bitmap(loadedImages[1]).width, Bitmap(loadedImages[1]).height);
alphaBmp.draw(loadedimage1);
var rect:Rectangle = new Rectangle(0, 0, 200, 200);
var pt:Point = new Point(20, 20);
var mult:uint = 0x80; // 50%
modelBmp.merge(alphaBmp, rect, pt, mult, mult, mult, mult);
var bm1:Bitmap = new Bitmap(load);
addChild(bm1);
bm1.x = 400;
var bm2:Bitmap = new Bitmap(alphaBmp);
addChild(bm2);
bm2.x = 200;}
}
}
I haven't checked to see if this works, so it might take a little messing with, the but basic idea should work for you. There are a bunch of ways to deal with chained conditional asset loading, this is a simple example.
Hope that helps -
This might seem a bit on the nose, but you can use the merge() method of the BitmapData class to merge two bitmaps images into one. There's an example using the merge() method at those links.
As far as saving to a local disk goes, Flash Player allows access to the file system using the FileReference class. The FileReference class has the save() method, which prompts the user to browse for a location on their file system.
For Air applications, you can access the file system by using the classes in the flash.filesystem package.