header
ask question
Click here to ask Question Now Its free No registration required. Flash, Flex, Flash Media Server, ActionScript,Adobe Air. Most questions receive a response in an hour.
Alex
Points:0
Posts:0
Answered

2/6/2011 7:20:51 AM

Title: Add image to sprite


Hi all

How can we add an image to a sprite in Flash Box2D in ActionScript?
I have the following code.But I don't know how to add an image into the sprite and set it to the userData of the bodyDef.


var sp:Sprite = new Sprite();
bodyDef.userData = sp;

Please give me a solution.



1
Efrain
Points: 0
Posts:0
Accepted Answer
2/6/2011 7:37:50 AM



You can create a class to load an image inside a sprite like this :


// class to load image in sprite
package
{
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.*;
import flash.net.URLRequest;
import mx.controls.Alert;

public class SpriteBitmap extends Sprite
{
	//path of image to be loaded
	private var url:String = "myImage.jpg";

	public function SpriteBitmap()
	{
		loadBitmap();
	}
	private function loadBitmap():void
	{
		var loader:Loader = new Loader();
		loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, imageFailed);
		var request:URLRequest = new URLRequest(url);
		loader.load(request);
		this.addChild(loader);
	}

	private function imageFailed(event:IOErrorEvent):void
	{
		Alert.show("Image loading failed");
	}
}

}

code for MXML:

//call this function in your MXML to use above class
private function createSpriteBitmap():void
	    {
	    var mySprite:SpriteBitmap = new SpriteBitmap();
	    //add sprite to  canvas container
	    myCanvas.rawChildren.addChild(mySprite);
	    }


2
btate
Points: 0
Posts:0
2/6/2011 7:43:57 AM



hi check this link for loading images inside sprite in flash

http://www.flashwonderland.com/load-external-image/load-image-2.html

3
Alex
Points: 0
Posts:0
2/6/2011 7:50:21 AM



Thanks Efrain, it worked.

4
Alex
Points: 0
Posts:0
2/6/2011 9:46:16 AM



But the image is never aligning with the body?
Is there any method for aligning it with the body?

5
Nathan
Points: 0
Posts:0
2/6/2011 10:30:28 AM



you can position the image using x, y properties

loader.x=100
loader.y =100

or you can create a new movieclip inside and sprite and loader to movieclip instead of adding it to root of sprite. Now you can position the movieclip using x and y properties .


Post your Reply
Name  

Email

Type your Reply or Answer

Are you human? What is 1+14+3 



Members Login

Email  
Password
Forgot Password





This website focus on: Flash | Flex | FMS | RED5 | WOWZA | Flash Media Server | Adobe AIR | ActionScript,Flash Solutions | Flash Question | Flash Answers | Flash Developers | Flash Problem, Flash Help, Flash bugs, Flash workaround | Flash Blog | Flex Question Answers | Flash Forum | Flex Development | Actionscript development | Flash development | Adobe AIR development
Copyright © 2008 AskMeFlash.com. All rights reserved. Privacy Policy | Terms & Conditions