How to change the pixels in an image - actionscript-3

i actually try to do the following: I have loaded an external image in a bitmapdata object and create a bitmap from it which i attach it to a sprite/MovieClip in order to have mouse events on it. Now under the previous logic i loaded two images (let's say circles) of the same size one that has a particular color and is covered by its black foreground circle. When i press left mouse button and hold it down i want while the mouse is moved to erase the foreground circle's pixels and so the background image starting to appear. I tried this to achieve but had no luck. In my best attempt i achieve to draw a line in the foreground image but i cannot reveal the background!
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.display.BlendMode;
public class Test2 extends MovieClip
{
// properties - state
// to attach the image and have mouse events
private var frontImage:Sprite;
private var backImage:Sprite;
// to load the image
private var myLoader:Loader;
// to get the bitmap data of the image
private var frontBitmapData:BitmapData;
private var frontBitmap:Bitmap;
// test
private var frontMask:Bitmap;
// constructor
function Test2():void
{
// load the background image
backImage = new Sprite();
attachImageToSprite1(new URLRequest("btest.jpg"));
backImage.mouseEnabled = false;
this.addChild( backImage );
// load the front image
frontImage = new Sprite();
attachImageToSprite2(new URLRequest("test.jpg"));
frontImage.mouseEnabled = true; // enable mouse
frontImage.buttonMode = true; // set button mode
this.addChild(frontImage); // load to stage
this.frontImage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
this.frontImage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
// methods
private function attachImageToSprite1(Name:URLRequest):void
{
this.myLoader = new Loader();
this.myLoader.load(Name);
this.myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete1);
}
private function attachImageToSprite2(Name:URLRequest):void
{
this.myLoader = new Loader();
this.myLoader.load(Name);
this.myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete2);
}
private function getImageBitmapDataFromSprite(srcImage:Sprite):BitmapData
{
var tmpBitmapData:BitmapData = new BitmapData(frontImage.width, frontImage.height, true, 0xFFCCCCCC);
tmpBitmapData.lock();
tmpBitmapData.draw(frontImage);
tmpBitmapData.unlock();
return tmpBitmapData;
}
private function isPixelAlpha(bitmapdata:BitmapData):Boolean
{
var pixelValue:uint = bitmapdata.getPixel32(mouseX, mouseY);
var alphaValue:uint = pixelValue >> 24 & 0xFF;
//var red:uint = pixelValue >> 16 & 0xFF;
//var green:uint = pixelValue >> 8 & 0xFF;
//var blue:uint = pixelValue & 0xFF;
return (alphaValue == 0x00) ? true : false;
}
private function deletePixelUnderMouse(bitmapdata:BitmapData, bitmap:Bitmap):void
{
bitmapdata.lock();
if ( !isPixelAlpha(bitmapdata) ) {
bitmapdata.setPixel32(mouseX, mouseY, 0xFF << 24); // how to make the current pixel's alpha
} // equal to zero.
bitmap = new Bitmap(bitmapdata);
bitmap.x = frontImage.x;
bitmap.y = frontImage.y;
this.frontImage.addChild(bitmap);
bitmapdata.unlock();
}
// events
public function onLoadComplete1(e:Event):void
{
frontImage.addChild(this.myLoader.content);
}
public function onLoadComplete2(e:Event):void
{
backImage.addChild(this.myLoader.content);
}
public function onMouseDown(e:MouseEvent):void
{
// delete a pixel from the sprite under the mouse
frontBitmapData = getImageBitmapDataFromSprite(frontImage);
deletePixelUnderMouse(frontBitmapData, frontBitmap);
frontImage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseDown);
trace("start");
}
public function onMouseUp(e:MouseEvent):void
{
frontImage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseDown);
trace("stop")
}
}
}

Not sure if I got it right, but if you want a 'reveal' effect, as in you draw a mask to display a hidden image for example, this could be achieved slightly easier:
var bitmapToReveal:BitmapData = new BitmapToReveal(0,0);
var brush:BitmapData = new Brush(0,0);
var canvasData:BitmapData = new BitmapData(bitmapToReveal.width,bitmapToReveal.height,true,0x00FFFFFF);
var cursor:Point = new Point();//used as destination point when painting
var zero:Point = new Point();//reused for painting
var reveal:Bitmap = new Bitmap(bitmapToReveal);
var canvas:Bitmap = new Bitmap(canvasData);
reveal.cacheAsBitmap = canvas.cacheAsBitmap = true;
addChild(reveal);
addChild(canvas);
reveal.mask = canvas;
stage.addEventListener(MouseEvent.MOUSE_DOWN, brushDown);
stage.addEventListener(MouseEvent.MOUSE_UP, brushUp);
function brushDown(event:MouseEvent):void {
this.addEventListener(Event.ENTER_FRAME, paint);
}
function brushUp(event:MouseEvent):void {
this.removeEventListener(Event.ENTER_FRAME, paint);
}
function paint(event:Event):void {
cursor.x = mouseX-brush.width*.5;
cursor.y = mouseY-brush.height*.5;
canvasData.copyPixels(brush,brush.rect,cursor,brush,zero,true);
}
I'm using two Bitmaps form the library(bitmapToReveal and brush).
The main thing to look at is the copyPixels() method. I copy
the brush bitmap into the canvas(an empty transparent bitmap data),
using the offset cursor position(so the brush centered), and using the
alpha channel to do that. Note that I've set cacheAsBitmap to true
for both mask and maskee. You need to do that to get a transparent mask,
which is key to the effect.
Here is the result:
You can 'paint' the mask here. CS4 Source is here.
HTH,
George

Related

Playing sounds on Actionscript

I have a simple drag and drop game started in flash and mostly working.
I have added my animals and you can drag and drop them in the right place.I have also added sound so that when the animal is dropped in the right spot , that is working however each time I add a new animal to the right spot it plays that sound and the last animal sound as well.
e.g. place pig in pig space , it plays pig sound
place cow in cow space , it plays cow sound and pig sound
place duck in duck space , it plays duck sound and cow sound and pig sound.
Obviously I only want to play the sound when the animal is placed in the right place - on drop ( not on next animal drop also )
I'm not sure what I have done wrong
/* Drag and Drop
Makes the specified symbol instance moveable with drag and drop.
*/
import flash.media.Sound;
var offset:int = 10;
var pigStartX:int = 196.80;
var pigStartY:int = 292.10;
var pigEndX:int = 578.40;
var pigEndY:int = 208.50;
Pig.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
function fl_ClickToDrag(event:MouseEvent):void
{
Pig.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void
{
Pig.stopDrag();
// dragging and dropping the pieces while checking for correct location
if(Pig.x < pigEndX - offset || Pig.x > pigEndX + offset || Pig.y < pigEndY - offset ||Pig.y > pigEndY + offset){
Pig.x = pigStartX;
Pig.y = pigStartY;
}
else{
//set piece back to original position
Pig.x = pigEndX;
Pig.y = pigEndY;
var oink:PigOink = new PigOink();
var channel:SoundChannel = oink.play();
//checkGame();
}
}
/* Drag and Drop
Makes the specified symbol instance moveable with drag and drop.
*/
var cowStartX:int = 324;
var cowStartY:int = 317.95;
var cowEndX:int = 411.50;
var cowEndY:int = 140.95;
Cow.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_2);
function fl_ClickToDrag_2(event:MouseEvent):void
{
Cow.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_2);
function fl_ReleaseToDrop_2(event:MouseEvent):void
{
Cow.stopDrag();
// dragging and dropping the pieces while checking for correct location
if(Cow.x < cowEndX - offset || Cow.x > cowEndX + offset || Cow.y < cowEndY - offset ||Cow.y > cowEndY + offset){
Cow.x = cowStartX;
Cow.y = cowStartY;
}
else{
//set piece back to original position
Cow.x = cowEndX;
Cow.y = cowEndY;
var moo:CowMoo = new CowMoo();
var channel:SoundChannel = moo.play();
//checkGame();
}
}
/* Drag and Drop
Makes the specified symbol instance moveable with drag and drop.
*/
var duckStartX:int = 209.45;
var duckStartY:int = 402.05;
var duckEndX:int = 56.45;
var duckEndY:int = 225.05;
Duck.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_3);
function fl_ClickToDrag_3(event:MouseEvent):void
{
Duck.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_3);
function fl_ReleaseToDrop_3(event:MouseEvent):void
{
Duck.stopDrag();
// dragging and dropping the pieces while checking for correct location
if(Duck.x < duckEndX - offset || Duck.x > duckEndX + offset || Duck.y < duckEndY - offset ||Duck.y > duckEndY + offset){
//set piece back to original position
Duck.x = duckStartX;
Duck.y = duckStartY;
}
else{
Duck.x = duckEndX;
Duck.y = duckEndY;
var quack:DuckQuack = new DuckQuack();
var channel:SoundChannel = quack.play();
//checkGame();
}
}
#Neal Davis is right about what is causing the problem, however I suggest to remove event listener once the animal is its destination position instead of listening MOUSE_UP event on the animal itself in release function:
function fl_ReleaseToDrop_3(event:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_3);
Pig.stopDrag();
//...
}
Aditional suggestion.
Also as #Organis pointed out. It's much simpler to have more generic code.
Consider having something like this:
Document class:
package
{
import flash.display.Sprite;
import flash.geom.Point;
public class Main extends Sprite
{
private var animals:Vector.<Animal> = Vector.<Animal>([]);
public function Main() {
animals.push(new Animal("pig", pigMc, 578, 208, "oink.mp3"));
animals.push(new Animal("cow", cowMc, 411, 140, "moo.mp3"));
animals.push(new Animal("duck", duckMc, 56, 225, "quack.mp3"));
}
}
}
And simple Animal class:
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.media.Sound;
import flash.net.URLRequest;
public class Animal
{
private var _name:String;
private var _dropMargin:Number = 10;
private var _startPos:Point = new Point();
private var _endPos:Point = new Point();
private var _sound:Sound;
private var _view:Sprite;
public function Animal(name:String, view:Sprite, endX:Number = 0, endY:Number = 0, sound:String = null) {
_name = name;
_view = view;
_startPos.x = _view.x; _startPos.y = _view.y;
_endPos.x = endX; _endPos.y = endY;
_sound = new Sound(new URLRequest(sound));
view.addEventListener(MouseEvent.MOUSE_DOWN, onMDown);
}
private function onMDown(e:MouseEvent):void{
_view.stage.addEventListener(MouseEvent.MOUSE_UP, onMUp);
_view.startDrag();
}
private function onMUp(e:MouseEvent):void {
_view.stage.removeEventListener(MouseEvent.MOUSE_UP, onMUp);
_view.stopDrag();
//Distance to destination point
var dd:Number = Point.distance(pos, _endPos);
if (dd > dropMargin) pos = _startPos;
else {
pos = _endPos;
_sound.play();
}
}
public function get view():Sprite{return _view;}
public function get dropMargin():Number{return _dropMargin;}
public function set dropMargin(value:Number):void{_dropMargin = value;}
public function get pos():Point{return new Point(_view.x, _view.y);}
public function set pos(value:Point):void{
_view.x = value.x;
_view.y = value.y;
}
}
}
Look at your MouseUp event handlers.
You are adding the event listener to the stage. So they are all getting called whenever the stage hears a mouse up event.
Add those listeners to the cow, pig etc just as you did for the mouse down listeners.
That should solve it.
Pig.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
function fl_ClickToDrag(event:MouseEvent):void
{
Pig.startDrag();
}
//stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
// change to this
Pig.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);

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.

Delete object border in flash animation / AS

I'm not familliar with flash neither action script, but i have to use a flash applet in my website, here is the object demo; http://www.weberdesignlabs.com/demos/flash_10_coverflow/
So the problem is, i want to disable the blank borders around each image, and also in the image reflection.
I think that when i'll get the image border itself to be disabled, the reflection border will be disabled too.
I of course have the .fla and all .as needed to modify that project.
What i tried, with succes is to set the blank border from 4 to 0 by modifing this line in the .as file called "Coverflow.as";
private var padding:Number=4;
The border will be effectively thinner, but the border is still here.
I paste you the Coverflow.as script code:
////////////////////////////////////////////
// Project: Flash 10 Coverflow
// Date: 10/3/09
// Author: Stephen Weber
////////////////////////////////////////////
package {
////////////////////////////////////////////
// IMPORTS
////////////////////////////////////////////
import flash.display.Sprite;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.display.GradientType;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.MovieClip;
import flash.display.BlendMode;
import flash.display.Loader;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.IOErrorEvent;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.geom.ColorTransform;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.net.navigateToURL;
import flash.display.Stage;
import flash.utils.setTimeout;
//TweenLite - Tweening Engine - SOURCE: http://blog.greensock.com/tweenliteas3/
import com.greensock.*;
import com.greensock.easing.*;
import com.greensock.plugins.*;
public class Coverflow extends Sprite {
////////////////////////////////////////////
// VARIABLES
////////////////////////////////////////////
// size of the stage
private var sw:Number;
private var sh:Number;
private var background:Background;
// padding between each cover, can be customed via xml
private var coverflowSpacing:Number=30;
// transition time for movement
private var transitionTime:Number=0.75;
// the center of the stage
private var centerX:Number;
private var centerY:Number;
// store each image cover's instance
private var coverArray:Array=new Array();
// title of each image
private var coverLabel:CoverflowTitle = new CoverflowTitle();
// the slider under the image cover
private var coverSlider:Scrollbar;
// how many image covers
private var coverflowItemsTotal:Number;
// how to open the link
private var _target:String;
// size of the image cover
private var coverflowImageWidth:Number;
private var coverflowImageHeight:Number;
//Holds the objects in the data array
private var _data:Array = new Array();
// the y position of the item's title
private var coverLabelPositionY:Number;
//Z Position of Current CoverflowItem
private var centerCoverflowZPosition:Number=-125;
// display the middle of the cover or not
private var startIndexInCenter:Boolean=true;
// which cover to display in the beginning
private var startIndex:Number=0;
// the slide's Y position
private var coverSlidePositionY:Number;
//Holder for current CoverflowItem
private var _currentCover:Number;
//CoverflowItem Container
private var coverflowItemContainer:Sprite = new Sprite();
//XML Loading
private var coverflowXMLLoader:URLLoader;
//XML
private var coverflowXML:XML;
// the image cover's white border padding
private var padding:Number=0;
// stage reference
private var _stage:Stage;
//reflection
private var reflection:Reflect;
//Reflection Properties
private var reflectionAlpha:Number;
private var reflectionRatio:Number;
private var reflectionDistance:Number;
private var reflectionUpdateTime:Number;
private var reflectionDropoff:Number;
////////////////////////////////////////////
// CONSTRUCTOR - INITIAL ACTIONS
////////////////////////////////////////////
public function Coverflow(_width:Number, _height:Number, __stage:Stage = null):void {
_stage=__stage;
sw=_width;
sh=_height;
centerX=_width>>1;
centerY=(_height>>1) - 20;
loadXML();
//Grabs Background color passed in through FlashVars
var backgColor:String = _stage.loaderInfo.parameters["backgroundColor"];
if(backgColor == null) {
//Black
backgColor = "0x000000";
//White
//backgColor = "0xFFFFFF";
}
//Creates Background MovieClip
background = new Background();
//Set Background To Provided Width/Height
background.width = _width;
background.height = _height;
//Adds background MovieClip to DisplayList
addChild(background);
//Tints Background MovieClip with provided tint
TweenPlugin.activate([TintPlugin]);
TweenLite.to(background, 0, {tint:backgColor});
//Grabs Background color passed in through FlashVars
var labelColor:String = _stage.loaderInfo.parameters["labelColor"];
//Check for value and then default
if(labelColor == null) {
//Black
//labelColor = "0x000000";
//White
labelColor = "0xFFFFFF";
}
//Tint Coverflow label to color provided
TweenLite.to(coverLabel, 0, {tint:labelColor});
if (_stage) {
_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
}
}
////////////////////////////////////////////
// FUNCTIONS
////////////////////////////////////////////
private function keyDownHandler(e:KeyboardEvent):void {
if (e.keyCode==37||e.keyCode==74) {
clickPre();
}
if (e.keyCode==39||e.keyCode==75) {
clickNext();
}
// 72 stand for "H" key, 191 stand for "?" key
if (e.keyCode==72||e.keyCode==191) {
}
}
// display the previous image
private function clickPre(e:Event=null):void {
_currentCover--;
if (_currentCover<0) {
_currentCover=coverflowItemsTotal-1;
}
coverSlider.value=_currentCover;
gotoCoverflowItem(_currentCover);
}
// display the next image
private function clickNext(e:Event=null):void {
_currentCover++;
if (_currentCover>coverflowItemsTotal-1) {
_currentCover=0;
}
coverSlider.value=_currentCover;
gotoCoverflowItem(_currentCover);
}
// loading the XML
private function loadXML():void {
//Loads XML passed through FlashVars
var xml_source:String = _stage.loaderInfo.parameters["xmlPath"];
//If XML not found through FlashVars then defaults to xml path below
if(xml_source == null) {
xml_source = 'xml/data.xml';
}
// loading the cover xml here
coverflowXMLLoader = new URLLoader();
coverflowXMLLoader.load(new URLRequest("xml/data.xml"));
coverflowXMLLoader.addEventListener(Event.COMPLETE, coverflowXMLLoader_Complete);
coverflowXMLLoader.addEventListener(IOErrorEvent.IO_ERROR, coverflowXMLLoader_IOError);
}
// parse the XML
private function coverflowXMLLoader_Complete(e:Event):void {
coverflowXML=new XML(e.target.data);
coverflowItemsTotal=coverflowXML.cover.length();
coverflowSpacing=Number(coverflowXML.#coverflowSpacing);
coverflowImageWidth=Number(coverflowXML.#imageWidth);
coverflowImageHeight=Number(coverflowXML.#imageHeight);
coverLabelPositionY=Number(coverflowXML.#coverLabelPositionY);
coverSlidePositionY=Number(coverflowXML.#coverSlidePositionY);
transitionTime=Number(coverflowXML.#transitionTime);
centerCoverflowZPosition=Number(coverflowXML.#centerCoverflowZPosition);
//Image Border
padding = Number(coverflowXML.#imagePadding)
//Reflection Attributes
reflectionAlpha=Number(coverflowXML.#reflectionAlpha);
reflectionRatio=Number(coverflowXML.#reflectionRatio);
reflectionDistance=Number(coverflowXML.#reflectionDistance);
reflectionUpdateTime=Number(coverflowXML.#reflectionUpdateTime);
reflectionDropoff=Number(coverflowXML.#reflectionDropoff);
startIndex=Number(coverflowXML.#startIndex);
startIndexInCenter = (coverflowXML.#startIndexInCenter.toLowerCase().toString()=="yes");
_target=coverflowXML.#target.toString();
for (var i=0; i<coverflowItemsTotal; i++) {
//Make An Object To Hold Values
var _obj:Object = new Object();
//Set Values To Object from XML for each CoverflowItem
_obj.image = (coverflowXML.cover[i].#img.toString());
_obj.title = (coverflowXML.cover[i].#title.toString());
_obj.link = (coverflowXML.cover[i].#link.toString());
_data[i] = _obj;
}
loadCover();
}
private function coverflowXMLLoader_IOError(event:IOErrorEvent):void {
trace("Coverflow XML Load Error: "+ event);
}
// load the image cover when xml is loaded
private function loadCover():void {
for (var i:int = 0; i < coverflowItemsTotal; i++) {
var cover:Sprite=createCover(i,_data[i].image);
coverArray[i]=cover;
cover.y=centerY;
cover.z=0;
coverflowItemContainer.addChild(cover);
}
if (startIndexInCenter) {
startIndex=coverArray.length>>1;
gotoCoverflowItem(startIndex);
} else {
gotoCoverflowItem(startIndex);
}
_currentCover=startIndex;
coverSlider=new Scrollbar(coverflowItemsTotal,_stage);
coverSlider.value=startIndex;
coverSlider.x = (_stage.stageWidth/2) - (coverSlider.width/2);
coverSlider.y=_stage.stageHeight-40;
coverSlider.addEventListener("UPDATE", coverSlider_Update);
coverSlider.addEventListener("PREVIOUS", coverSlider_Previous);
coverSlider.addEventListener("NEXT", coverSlider_Next);
addChild(coverSlider);
//coverLabel.x = (sw - coverLabel.width)>>1;
coverLabel.x = (_stage.stageWidth/2) - (coverLabel.width/2);
coverLabel.y=coverLabelPositionY;
addChild(coverLabel);
addChild(coverSlider);
addChild(coverLabel);
}
private function coverSlider_Update(e:Event):void {
var value:Number=(coverSlider.value);
gotoCoverflowItem(value);
e.stopPropagation();
}
private function coverSlider_Previous(e:Event):void {
clickPre();
}
private function coverSlider_Next(e:Event):void {
clickNext();
}
// move to a certain cover via number
private function gotoCoverflowItem(n:int):void {
_currentCover=n;
reOrderCover(n);
if (coverSlider) {
coverSlider.value=n;
}
}
private function cover_Selected(event:CoverflowItemEvent):void {
var currentCover:uint=event.data.id;
if (coverArray[currentCover].rotationY==0) {
try {
// open the link if user click the cover in the middle again
if (_data[currentCover].link!="") {
navigateToURL(new URLRequest(_data[currentCover].link), _target);
}
} catch (e:Error) {
//
}
} else {
gotoCoverflowItem(currentCover);
}
}
// change each cover's position and rotation
private function reOrderCover(currentCover:uint):void {
for (var i:uint = 0, len:uint = coverArray.length; i < len; i++) {
var cover:Sprite=coverArray[i];
if (i<currentCover) {
//Left Side
TweenLite.to(cover, transitionTime, {x:(centerX - (currentCover - i) * coverflowSpacing - coverflowImageWidth/2), z:(coverflowImageWidth/2), rotationY:-65});
} else if (i > currentCover) {
//Right Side
TweenLite.to(cover, transitionTime, {x:(centerX + (i - currentCover) * coverflowSpacing + coverflowImageWidth/2), z:(coverflowImageWidth/2), rotationY:65});
} else {
//Center Coverflow
TweenLite.to(cover, transitionTime, {x:centerX, z:centerCoverflowZPosition, rotationY:0});
//Label Handling
coverLabel._text.text=_data[i].title;
coverLabel.alpha=0;
TweenLite.to(coverLabel, 0.75, {alpha:1,delay:0.2});
}
}
for (i = 0; i < currentCover; i++) {
addChild(coverArray[i]);
}
for (i = coverArray.length - 1; i > currentCover; i--) {
addChild(coverArray[i]);
}
addChild(coverArray[currentCover]);
if (coverSlider) {
addChild(coverSlider);
addChild(coverLabel);
}
}
//Create CoverflowItem and Set Data To It
private function createCover(num:uint, url:String):Sprite {
//Setup Data
var _data:Object = new Object();
_data.id=num;
//Create CoverflowItem
var cover:CoverflowItem=new CoverflowItem(_data);
//Listen for Click
cover.addEventListener(CoverflowItemEvent.COVERFLOWITEM_SELECTED, cover_Selected);
//Set Some Values
cover.name=num.toString();
cover.image=url;
//cover.padding=padding;
cover.imageWidth=coverflowImageWidth;
cover.imageHeight=coverflowImageHeight;
cover.setReflection(reflectionAlpha, reflectionRatio, reflectionDistance, reflectionUpdateTime, reflectionDropoff);
//Put CoverflowItem in Sprite Container
var coverItem:Sprite = new Sprite();
cover.x=- coverflowImageWidth/2-padding;
cover.y=- coverflowImageHeight/2-padding;
coverItem.addChild(cover);
coverItem.name=num.toString();
return coverItem;
}
}
}
Note that there is 6 more script file, named: CoverflowItem.as, CoverflowItemEvent.as, Main.as, Reflect.as, Scrollbar.as, ScrollbarEvent.as.
I hope the solution is in the script file above.
If someone who's familliar with AS can point me in a good direction to go, i will be very pleased !
Sorry if my english isnt very good.
This component loads settings from a file called data.xml. Setting imagePadding="0" in that XML file should get rid of the border.

As3 magnify image

I want to create a image magnify application like following:
A masked small window showig big image area corresponding to the mouse X and Y on the small image. There are many magnifying image application exaples online such as:
http://www.flashandmath.com/intermediate/magglass/mag_glass.html
But here the mouse and mask moves with same X and Y. What i want is that masked window display only certain area corresponding to mouse X and Y on Small image.
Any help would be highly appreciated. thanks.
i wrote a recipe last year for exactly what you're looking for. i do not guarantee that's it's as refactored or efficient as it could be, but it works really well. change it up as much as you like. i post the code hear for anyone to freely use.
however, the photograph and loupe asset i do not permit anyone to use without prior request, please.
the class lets you alter your own magnification strength, even at runtime if you want. you can use your own loupe graphic, but one is also included in the source files (please ask me first if you want to use it in your project).
Description:
Magnifier: Creating A Customizable
Magnifier For Image Assets
The following code demonstrates the
solution for creating a customizable
magnifier for image assets using the
Magnifier class.
The Magnifier constructor receives 6
parameters. The first
loupeDisplayObject:DisplayObject
required parameter is a reference to a
display object that is used as the
virtual loupe. In order for the class
to function properly, the
loupeDisplayObject:DisplayObject must
contain a circular or elliptically
shaped void or alpha transparency at
its center.
The second imageURL:String required
parameter supplies the URLLoader’s
load function’s URLRequest with the
URL of the target image asset. The
image provides BitmapData for both
thumbSprite:Sprite and
magnificationSprite:Sprite objects,
which are scaled using the third
thumbScale:Number and fourth
magnificationScale:Number optional
parameters. The scale of the
thumbSprite:Sprite is exhibited on
stage, while the scale of the
magnificationSprite:Sprite is visible
during magnification.
The Magnifier class operates by
employing mouse events to toggle the
visibility of a virtual loupe over an
image asset. A maskSprite:Sprite
ellipse, both indexed below and based
on the size of the
loupeDisplayObject:DisplayObject, is
created to mask the
magnificationSprite:Sprite. However,
the fifth maskWidth:Number and sixth
maskHeight:Number optional parameters
can be set to manually size a
maskSprite:Sprite that is more
suitable for a
loupeDisplayObject:DisplayObject with
a complex shape.
Calling the public deallocate()
function of the Magnifier instance
prior to its nullification will mark
it as being available for garbage
collection.
Class FIle:
package
{
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.ui.Mouse;
import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.Regular;
public class Magnifier extends Sprite
{
//Class Variables
private var loupeDisplayObject:DisplayObject;
private var imageWidth:Number;
private var imageHeight:Number;
private var thumbScale:Number;
private var magnificationScale:Number;
private var maskWidth:Number;
private var maskHeight:Number;
private var imageBitmapData:BitmapData;
private var maskSprite:Sprite;
private var magnificationSprite:Sprite;
private var thumbSprite:Sprite;
private var loupeTween:Tween;
private var magnificationTween:Tween;
//Constructor
public function Magnifier (
loupeDisplayObject:DisplayObject,
imageURL:String,
thumbScale:Number = 0.5,
magnificationScale:Number = 1.0,
maskWidth:Number = NaN,
maskHeight:Number = NaN
)
{
this.loupeDisplayObject = loupeDisplayObject;
this.thumbScale = Math.max(0.1, Math.min(thumbScale, 1.0));
this.magnificationScale = Math.max(0.1, magnificationScale);
this.maskWidth = maskWidth;
this.maskHeight = maskHeight;
init(imageURL);
}
//Load And Handle Image
private function init(imageURL:String):void
{
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageHandler);
imageLoader.load(new URLRequest(imageURL));
}
private function errorHandler(evt:IOErrorEvent):void
{
throw(evt.text);
}
private function imageHandler(evt:Event):void
{
evt.target.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
evt.target.removeEventListener(Event.COMPLETE, imageHandler);
imageWidth = evt.target.content.width;
imageHeight = evt.target.content.height;
imageBitmapData = new BitmapData(imageWidth, imageHeight);
imageBitmapData.draw(evt.target.content);
createComponents();
}
//Create Components
private function createComponents():void
{
//Loupe Visibility
loupeDisplayObject.alpha = 0;
//Mask
if (isNaN(maskWidth)) maskWidth = loupeDisplayObject.width;
if (isNaN(maskHeight)) maskHeight = loupeDisplayObject.height;
maskSprite = new Sprite();
maskSprite.graphics.beginFill(0x00FF00, 0.5);
maskSprite.graphics.drawEllipse(0, 0, maskWidth, maskHeight);
maskSprite.graphics.endFill();
maskSprite.mouseEnabled = false;
//Magnification
magnificationSprite = scaleImage(new Matrix(magnificationScale, 0, 0, magnificationScale));
magnificationSprite.mouseEnabled = false;
magnificationSprite.alpha = 0;
magnificationSprite.mask = maskSprite;
//Thumb
thumbSprite = scaleImage(new Matrix(thumbScale, 0, 0, thumbScale));
thumbSprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
//Add Components To The Display List
addChild(thumbSprite);
addChild(magnificationSprite);
addChild(maskSprite);
addChild(loupeDisplayObject);
}
private function scaleImage(matrix:Matrix):Sprite
{
var scaledResult:Sprite = new Sprite();
scaledResult.graphics.beginBitmapFill(imageBitmapData, matrix, false, true);
scaledResult.graphics.drawRect(0, 0, imageWidth * matrix.a, imageHeight * matrix.d);
scaledResult.graphics.endFill();
return scaledResult;
}
//Mouse Event Handlers
private function mouseDownHandler(evt:MouseEvent):void
{
thumbSprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
thumbSprite.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
mouseMoveHandler(evt);
setLoupeAsVisible(true);
}
private function mouseMoveHandler(evt:MouseEvent):void
{
loupeDisplayObject.x = evt.localX - loupeDisplayObject.width / 2;
loupeDisplayObject.y = evt.localY - loupeDisplayObject.height / 2;
maskSprite.x = evt.localX - maskSprite.width / 2;
maskSprite.y = evt.localY - maskSprite.height / 2;
magnificationSprite.x = 0 - evt.localX / thumbSprite.width * (magnificationSprite.width - thumbSprite.width);
magnificationSprite.y = 0 - evt.localY / thumbSprite.height * (magnificationSprite.height - thumbSprite.height);
}
private function mouseOutHandler(evt:MouseEvent):void
{
thumbSprite.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
setLoupeAsVisible(false);
}
private function mouseOverHandler(evt:MouseEvent):void
{
thumbSprite.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
setLoupeAsVisible(true);
}
private function mouseUpHandler(evt:MouseEvent):void
{
if (thumbSprite.hasEventListener(MouseEvent.MOUSE_OVER)) thumbSprite.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
thumbSprite.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
thumbSprite.removeEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
setLoupeAsVisible(false);
}
//Loupe Tween And Visibility
private function setLoupeAsVisible(response:Boolean):void
{
var targetAlpha:Number;
if (response)
{
targetAlpha = 1.0;
Mouse.hide();
}
else
{
targetAlpha = 0.0;
Mouse.show();
}
loupeTween = new Tween(loupeDisplayObject, "alpha", Regular.easeIn, loupeDisplayObject.alpha, targetAlpha, 0.25, true);
magnificationTween = new Tween(magnificationSprite, "alpha", Regular.easeIn, magnificationSprite.alpha, targetAlpha, 0.25, true);
}
//Clean Up
public function deallocate():void
{
thumbSprite.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
}
}

positioning bitmapdata

I have the following code:
public function Application()
{
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
var urlRequest:URLRequest = new URLRequest("image/1.jpg");
loader.load(urlRequest);
addChild(loader);
}
private function completeHandler(e:Event):void{
loader.content.width = 800;
loader.content.scaleY = loader.content.scaleX;
piece = Math.round(loader.height/10);
drawBitmaps();
}
private function drawBitmaps():void{
var bmdata:BitmapData = new BitmapData(loader.width, piece, true, 0x000000);
bmdata.draw(loader);
var bitmap:Bitmap = new Bitmap(bmdata);
addChild(bitmap);
loader.visible = false;
}
the result is a bitmap wich contains a pice of the image. The height is 80. and it starts at the top of the image. But how can i tell the bitmapdata to start drawing the image from lets say 80pixels? so it draws a middle piece of the image? Because atm it allways draws from the top of the image.
You should use BitmapData::draw clipRect parameter.
Here is an example:
package {
import flash.geom.Rectangle;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Graphics;
import flash.display.Sprite;
public class BitmapDataTest extends Sprite {
public function BitmapDataTest() {
var c:Sprite = new Sprite();
var g:Graphics;
g = c.graphics;
g.beginFill(0xFF0000);
g.drawCircle(30,30,30);
g.endFill();
addChild(c);
c.x = 10;
c.y = 10;
var bmdata:BitmapData = new BitmapData(60, 60, true, 0x000000);
bmdata.draw(c,null,null,null, new Rectangle(0,30,30,30));
var bitmap:Bitmap = new Bitmap(bmdata);
addChild(bitmap);
bitmap.x = 80;
bitmap.y = 10;
}
}
}
Please notice that the target bitmap data should have the same dimensions as source or this won't work. If you really have to cut it down you should use BitmapData::copyPixels method.
The easiest way would be to apply a mask, dynamically. Here is a good example: Actionscript 3 and dynamic masks
You can create a rectangle, the height you're looking for and position it appropriately.
Hope this helps.