setting Brightness Contrast Hue Saturation for a specific element with FLEX - actionscript-3

I'm trying to allow the user to set the Brightness, Contrast, Hue, and Saturation for the remote users Camera (this will just affect the local user that is adjusting the preferences) with a Slider. I don't see a class for this here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/Camera.html# so I used the libraries below to set the element "remoteVideo" (the remote camera) to whatever the user desires for Brightness, Contrast, Hue, and Saturation. I'm getting a syntax error for color.brightness.remoteVideo(0, BrightnessSlider.value); (and for Contrast, Hue, and Saturation) that says (Multiple Markers at this Line. 1119: Access of Undefined property brightess through a reference with fl.motion.adjustcolor & - Access of undefined property remoteVideo, which is clearly defined since the RTMFP Video Chat works\compiles fine without the code below:
( Original Sourcecode without my changes below if it helps: https://github.com/MonaSolutions/MonaClients/blob/master/VideoPhone/src/VideoPhone.mxml )
// Libraries for Brightness Contrast Hue Saturation
import flash.display.Sprite;
import fl.motion.AdjustColor;
import flash.filters.ColorMatrixFilter;
import fl.events.SliderEvent;
import flash.external.ExternalInterface;
// variables for Brightness Contrast Hue Saturation
private var color:AdjustColor = new AdjustColor(); //This object will hold the color properties
private var filter:ColorMatrixFilter; //Will store the modified color filter to change the video
// FIXED functions
private function BrightnessLevel(e:Event = null):void
{
color.brightness = BrightnessSlider.value;
var mMatrix:Array = color.CalculateFinalFlatArray();
filter = new ColorMatrixFilter(mMatrix);
remoteVideo.filters = [filter];
status("Setting brightness to: " + BrightnessSlider.value + "\n");
}
private function ContrastLevel(e:Event = null):void
{
color.contrast = ContrastSlider.value;
var mMatrix:Array = color.CalculateFinalFlatArray();
filter = new ColorMatrixFilter(mMatrix);
remoteVideo.filters = [filter];
status("Setting contrast to: " + ContrastSlider.value + "\n");
}
private function HueLevel(e:Event = null):void
{
color.hue = HueSlider.value;
var mMatrix:Array = color.CalculateFinalFlatArray();
filter = new ColorMatrixFilter(mMatrix);
remoteVideo.filters = [filter];
status("Setting hue to: " + HueSlider.value + "\n");
}
private function SaturationLevel(e:Event = null):void
{
color.saturation = SaturationSlider.value;
var mMatrix:Array = color.CalculateFinalFlatArray();
filter = new ColorMatrixFilter(mMatrix);
remoteVideo.filters = [filter];
status("Setting saturation to: " + SaturationSlider.value + "\n");
}
// sliders for Brightness Contrast Hue Saturation
<s:NavigatorContent label="ADJUST COLORS" enabled="{currentState != LoginNotConnected}">
<s:layout>
<s:HorizontalLayout/>
</s:layout>
<s:VGroup>
<s:HGroup>
<s:Panel width="247" height="67.5" backgroundColor="0xA0A0A0"
title="Brightness">
<s:layout>
<s:VerticalLayout paddingLeft="8"/>
</s:layout>
<s:HSlider id="BrightnessSlider" width="220"
change="BrightnessLevel(event)" maximum="100" minimum="-100"
showDataTip="false" value="0"/>
</s:Panel>
<s:Panel width="247" height="67.5" backgroundColor="0xA0A0A0"
title="Contrast">
<s:layout>
<s:VerticalLayout paddingLeft="8"/>
</s:layout>
<s:HSlider id="ContrastSlider" width="220" change="ContrastLevel(event)"
maximum="100" minimum="-100" showDataTip="false" value="0"/>
</s:Panel>
</s:HGroup>
<s:HGroup>
<s:Panel width="247" height="67.5" backgroundColor="0xA0A0A0" title="Hue">
<s:layout>
<s:VerticalLayout paddingLeft="8"/>
</s:layout>
<s:HSlider id="HueSlider" width="220" change="HueLevel(event)"
maximum="180" minimum="-180" showDataTip="false" value="0"/>
</s:Panel>
<s:Panel width="247" height="67.5" backgroundColor="0xA0A0A0"
title="Saturation">
<s:layout>
<s:VerticalLayout paddingLeft="8"/>
</s:layout>
<s:HSlider id="SaturationSlider" width="220"
change="SaturationLevel(event)" maximum="100" minimum="-100"
showDataTip="false" value="0"/>
</s:Panel>
</s:HGroup>
</s:VGroup>
</s:NavigatorContent>

Based on the documentation for AdjustColor, each of those properties (brightness, contrast, hue, saturation) is a Number. So this line:
color.brightness.remoteVideo(0, BrightnessSlider.value);
is trying to access the property remoteVideo from color.brightness which is a Number. It's telling you that there is no property "remoteVideo" on Number.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/fl/motion/AdjustColor.html
Edit:
Something like this may or may not work: (I haven't tested this)
color.brightness = BrightnessSlider.value;
var mMatrix:Array = color.CalculateFinalFlatArray();
filter = new ColorMatrixFilter(mMatrix);
remoteVideo.filters = [filter];
You can avoid creating a new Filter constantly by instantiating it once and just updating its matrix property.
private var color:AdjustColor = new AdjustColor(); //This object will hold the color properties
private var filter:ColorMatrixFilter = new ColorMatrixFilter(); //Will store the modified color filter to change the video
private function BrightnessLevel(e:Event = null):void
{
status("Setting brightness to: " + BrightnessSlider.value + "\n");
color.brightness = BrightnessSlider.value;
applyFilter();
}
private function ContrastLevel(e:Event = null):void
{
status("Setting contrast to: " + ContrastSlider.value + "\n");
color.contrast = ContrastSlider.value;
applyFilter();
}
private function HueLevel(e:Event = null):void
{
status("Setting hue to: " + HueSlider.value + "\n");
color.hue = HueSlider.value;
applyFilter();
}
private function SaturationLevel(e:Event = null):void
{
status("Setting saturation to: " + SaturationSlider.value + "\n");
color.saturation = SaturationSlider.value;
applyFilter();
}
private function applyFilter():void
{
filter.matrix = color.CalculateFinalFlatArray();
remoteVideo.filters = [filter];
}

Related

Button is not functioning properly (Resetting AdjustColors)

I'm using AdjustColor\ColorMatrixFilter to change the Color (Brightness, Contrast, Hue, Saturation) of an Element (remoteVideo), which is controlled using Sliders.
My issue is when the button with the label RESET COLORS is clicked the four sliders
BrightnessSlider.value = 0;
ContrastSlider.value = 0;
HueSlider.value = 0;
SaturationSlider.value = 0;
do move back to their default position of 0, but only the Contrast and Saturation is reset. I've also tried removing the call to the function adjustColor() and repeating the same steps contained within that function without success.
Update: I also tried filter.matrix = null;
remoteVideo.filters = null; but the same issue still stands.
Libraries:
import flash.display.Sprite;
import fl.motion.AdjustColor;
import flash.filters.ColorMatrixFilter;
import fl.events.SliderEvent;
import flash.external.ExternalInterface;
Variables:
// color change
private var color:AdjustColor = new AdjustColor(); //This object will hold the color properties
private var filter:ColorMatrixFilter = new ColorMatrixFilter(); //Will store the modified color filter to change the video
Function:
private function resetColors(e:Event = null):void
{
// reset all sliders to 0
BrightnessSlider.value = 0;
ContrastSlider.value = 0;
HueSlider.value = 0;
SaturationSlider.value = 0;
adjustColor();
}
private function adjustColor(e:Event = null):void
{
color.brightness = BrightnessSlider.value;
color.contrast = ContrastSlider.value;
color.hue = HueSlider.value;
color.saturation = SaturationSlider.value;
filter.matrix = color.CalculateFinalFlatArray();
remoteVideo.filters = [filter];
}
GUI:
<s:NavigatorContent label="ADJUST COLORS" enabled="{currentState != LoginNotConnected}">
<s:layout>
<s:HorizontalLayout/>
</s:layout>
<s:VGroup>
<s:HGroup>
<s:Panel width="247" height="67.5" backgroundColor="0xA0A0A0"
title="Brightness">
<s:layout>
<s:VerticalLayout paddingLeft="8"/>
</s:layout>
<s:HSlider id="BrightnessSlider" width="220" change="adjustColor(event)" maximum="100" minimum="-100" showDataTip="false" value="0"/>
</s:Panel>
<s:Panel width="247" height="67.5" backgroundColor="0xA0A0A0"
title="Contrast">
<s:layout>
<s:VerticalLayout paddingLeft="8"/>
</s:layout>
<s:HSlider id="ContrastSlider" width="220" change="adjustColor(event)"
maximum="100" minimum="-100" showDataTip="false" value="0"/>
</s:Panel>
</s:HGroup>
<s:HGroup>
<s:Panel width="247" height="67.5" backgroundColor="0xA0A0A0" title="Hue">
<s:layout>
<s:VerticalLayout paddingLeft="8"/>
</s:layout>
<s:HSlider id="HueSlider" width="220" change="adjustColor(event)" maximum="180" minimum="-180" showDataTip="false" value="0"/>
</s:Panel>
<s:Panel width="247" height="67.5" backgroundColor="0xA0A0A0"
title="Saturation">
<s:layout>
<s:VerticalLayout paddingLeft="8"/>
</s:layout>
<s:HSlider id="SaturationSlider" width="220"
change="adjustColor(event)" maximum="100" minimum="-100" showDataTip="false" value="0"/>
</s:Panel>
</s:HGroup>
<s:Button label="RESET COLORS" click="resetColors(event)" styleName="buttonStyle"/>
</s:VGroup>
</s:NavigatorContent>
In your resetColors function you don't need the call to adjustColor. Remove it and replace it with remoteVideo.filters = null;
private function resetColors(e:Event = null):void
{
// reset all sliders to 0
BrightnessSlider.value = 0;
ContrastSlider.value = 0;
HueSlider.value = 0;
SaturationSlider.value = 0;
remoteVideo.filters = null;
}

Increase height of reflected object

Want to reflect an image, and my code looks like
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
height="500" width="500"
creationComplete="init(event)">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import flash.filters.BlurFilter;
import mx.core.UIComponent;
import mx.events.FlexEvent;
private var loader:Loader = new Loader();
private var picture:BitmapData;
private var reflection:BitmapData;
private var reflectionHolder:Bitmap;
protected function init(event:FlexEvent):void
{
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.load(new URLRequest("assets/rectangle.png"));
}
private function onComplete (event:Event):void
{
trace("loaded!");
var loaderInfo:LoaderInfo = LoaderInfo(event.target);
picture = new BitmapData(loaderInfo.width, loaderInfo.height, false, 0xFFFFFF);
picture.draw(loaderInfo.loader);
img.source=picture;
trace(picture.height,picture.width);
}
private function createReflection():void
{
reflection=new BitmapData(picture.width,picture.height,true,0x00ffffff);
var flipMatrix:Matrix = new Matrix();
flipMatrix.rotate(Math.PI);
flipMatrix.scale( -1, 1 );
flipMatrix.translate(0, picture.height);
reflection.draw(picture, flipMatrix);
for (var i:int = 0; i < picture.height; i++)
{
var rowFactor:Number = Math.max(0, 1 - (i / picture.height));
for (var j:int = 0; j < picture.width; j++)
{
var pixelColor:uint = reflection.getPixel32(j,i);
var pixelAlpha:uint = pixelColor>>24&0xff;
var pixelRGB:uint = pixelColor&0xffffff;
var resultAlpha:uint = pixelAlpha*rowFactor;
reflection.setPixel32(j, i, resultAlpha << 24 | pixelRGB);
}
}
reflection.applyFilter(reflection, reflection.rect, new Point(0, 0), new BlurFilter(4, 4, 3));
reflectionHolder=new Bitmap(reflection);
reflectionHolder.y=img.y+img.height;
reflectionHolder.x=img.x;
reflectionHolder.width = img.width;
reflectionHolder.height = img.height;
var uIComponent:UIComponent = new UIComponent();
uIComponent.addChild(reflectionHolder);
this.addElement(uIComponent);
}
protected function btn_clickHandler(event:MouseEvent):void
{
createReflection();
}
]]>
</fx:Script>
<s:Group height="100%" width="100%">
<s:BorderContainer backgroundColor="0x0d0d0d" height="100%" width="100%"/>
<s:Image id="img" height="100" width="200" />
<s:Button id="btn" click="btn_clickHandler(event)" />
</s:Group>
</s:WindowedApplication>
it shows result but the out put was not perfect...
Objective:- Reflected object should be same as the real Object and Have Some Distance From Real Object.
It will be very much code to show in one answer. Actually, I searched my very old archives, and I found my old class for reflection (2009 year). It will create reflection for you, It supports animated objects, and also distance from object to start of reflection. With only 2 lines of code:
var test:Sprite = new Sprite();
test.graphics.beginFill(0x990099);
test.graphics.drawRect(0, 0, 100, 50);
addChild(test);
test.x = test.y = 50;
//Reflection
//test - object that will be reflected
//40 - alpha, 40%
//200 - ratio, max value 0xFF or 255, with 0xFF you will see full object in reflection
//-1 - update frame rate, for animated objects
//0 - some dropoff... actually I don't remember it, don't use it by passing zero, It affects reflection bounds
//10 - distance to the reflection in pixels...
var vars:ReflectVars = new ReflectVars(test, 40, 200, -1, 0, 10);
var reflect:Reflect = new Reflect(vars);
And a result:
if you are interested in the class, I could move it to GitHub.
flipMatrix.translate(0, picture.height);
try changing this to
flipMatrix.translate(0, picture.height + 20);
OR
reflectionHolder.y=img.y+img.height;
try changing this to
reflectionHolder.y=img.y+img.height + 20;
for adding space between reflection & real picture

How to play an m4a sound file

The code below imports and controls an mp3 sound file. When I change from an mp3 to an m4a file the code does not work. Do I need to use a different class to play an m4a file?
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600" creationComplete="init()" >
<mx:Script>
<![CDATA[
import mx.events.ItemClickEvent;
import mx.rpc.events.ResultEvent;
private var sound:Sound;
private var soundChannel:SoundChannel = new SoundChannel;
private var loaderContext:SoundLoaderContext;
private var trackPosition:Number = 0;
private var timer:Timer;
private var leftGraphic:Sprite;
private var rightGraphic:Sprite;
private function init():void{
var audioFile:String = "recording.mp3";
sound = new Sound(new URLRequest(audioFile));
sound.addEventListener(Event.COMPLETE, onSoundLoaded);
function onSoundLoaded(event:Event):void{
maxTime.text = convertMillesecs(sound.length)
trackSlider.y-= 5;
trackSlider.maximum = sound.length;
}
}
private var counter:Number
private function soundComplete( e:Event ):void{
maxTime.text = convertMillesecs(soundChannel.position);
maxTime.text = convertMillesecs(sound.length)
}
private function checkTrack(event:Event):void{
// manage track counter
trackSlider.value = soundChannel.position;
currentVal.text = String(convertMillesecs(soundChannel.position));
}
private function convertMillesecs(time:Number):String{
var h:Number = new Number(Math.floor(time/1000/60/60));
var m:Number = new Number(Math.floor(time/1000/60)-(h*60));
var s:Number = new Number(Math.floor(time/1000)-(m*60));
var hours:String;
var minutes:String;
var seconds:String
//minutes and seconds always two digits
if(m.toString().length == 1) {
minutes = "0"+m;
} else {
minutes = m.toString();
}
if(s.toString().length == 1) {
seconds = "0"+s;
} else {
seconds = s.toString();
}
// last two digits represent actual seconds
seconds = seconds.slice(seconds.length-2, seconds.length);
return minutes + ":" + seconds;
}
private function controlChange1(event:MouseEvent):void{
var optionString:String;
switch(event.target.id){
case "playButton":
play();
break;
case "pauseButton":
pause();
break;
default:
break;
}
}
private function play():void{
playButton.visible = false;
pauseButton.visible = true;
timer = new Timer(100);
timer.addEventListener(TimerEvent.TIMER, checkTrack);
soundChannel.stop();
soundChannel = sound.play(pausePosition);
timer.start();
}
private var pausePosition:int
private function pause():void{
pausePosition = soundChannel.position;
soundChannel.stop();
playButton.visible = true;
pauseButton.visible = false;
}
private function onTrackSliderChange(e:Event):void{
soundChannel.stop()
soundChannel = sound.play(e.target.value * sound.length / trackSlider.maximum);
playButton.visible = false;
pauseButton.visible = true;
}
private function formatButton(val:String):String{
return convertMillesecs(soundChannel.position)
}
]]>
</mx:Script>
<mx:HBox backgroundColor="0x000000" horizontalCenter="0" verticalCenter="0" verticalAlign="middle" horizontalScrollPolicy="off" verticalScrollPolicy="off" >
<mx:Canvas id="controlBar1" paddingLeft="1" buttonMode="true" useHandCursor="true" >
<mx:Button id="pauseButton" width="40" height="40" click="controlChange1(event)" visible="false" color="0x0B333C"/>
<mx:Button id="playButton" width="40" height="40" click="controlChange1(event)" color="0x000000" />
</mx:Canvas>
<mx:Label id="currentVal" text="00:00" color="0xffffff"/>
<mx:HSlider id="trackSlider" height="10" width="500" liveDragging="false" change="onTrackSliderChange(event);"
dataTipFormatFunction="formatButton" showTrackHighlight = "true" mouseEnabled="true" useHandCursor="true" />
<mx:Label id="maxTime" text="00:00" color="0xffffff"/>
</mx:HBox>
</mx:Application>
The Sound class can play one of two formats: mp3 and the raw format AS3 records to. So it is impossible to use the Sound class to play m4a, unfortunately.
Fortunately, it is possible to play m4a using another class: NetStream. You may or may not have as fine of control over it without the SoundTransform and SoundMixer classes, but you can still play the file no problem (I've done it in the past, though it didn't end up working quite the way I was hoping for so I ended up going with mp3s instead)
Adobe Article on m4a playback

Flex 4 Spark List Itemrender

Here is my itemRenderer:
<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
autoDrawBackground="true"
width="100%" height="40"
click="adCanvas.selected=data.object;" mouseDown="adCanvas.selected=data.object;"
creationComplete="init()" initialize="trace('initializing')" activate="checkActions()" dataChange="checkActions()" render="checkActions()">
<fx:Script>
<![CDATA[
import adBuilder.*;
import components.AdCanvas;
import events.AdLoadEvent;
import flash.display.Bitmap;
import flash.events.MouseEvent;
import flash.utils.describeType;
import interfaces.IAdObject;
import mx.core.FlexGlobals;
import mx.core.UIComponent;
import mx.events.CollectionEvent;
import mx.utils.*;
[Bindable] private var desc:String;
private var adCanvas:AdCanvas;
private var adBuilder:AdBuilder;
[Bindable]private var myvis:Boolean=false;
private const MAX_NAME_LENGTH:Number = 19;
private function init():void {
trace("!!!!!!!!!!!!!!!!!!!!! LAYER RENDERER !!!!!!!!!!!!!!!!!!!!!");
if (!data) data = {};
if (data.hasOwnProperty("first")) {
toggleEnabled(FlexGlobals.topLevelApplication.btnUp);
}
if (data.hasOwnProperty("last")) {
toggleEnabled(FlexGlobals.topLevelApplication.btnDown);
}
adCanvas = data.adCanvas;
if(IAdObject(data.object as IAdObject)){
if(IAdObject(data.object).animationObjects){
IAdObject(data.object).animationObjects.addEventListener(CollectionEvent.COLLECTION_CHANGE, checkActions);
checkActions();
}
}
iconType.source = findSource();
}
private function checkActions(e:Event=null):void{
try{
if(data){
if(IAdObject(data.object as IAdObject)){
if(IAdObject(data.object as IAdObject).animationObjects){
if(data.object.animationObjects.length>0){
this.myvis=true;
}else{
this.myvis=false;
}
}
}
}
iconType.source = findSource();
}catch(error:Error){
trace("LayerRenderer.mxml - checkActions(): " + error.message);
}
}
private function toggleEnabled(obj:UIComponent):void {
if (data.hasOwnProperty("first")) {
obj.useHandCursor = false;
obj.enabled = false;
obj.alpha = 0.5;
} else {
obj.useHandCursor = true;
obj.enabled = true;
obj.alpha = 1;
}
iconType.source = findSource();
}
private function hideLayers():void{
//dispatchEvent(new Event("Layer_Visible"));
trace("CLICKED EYE");
FlexGlobals.topLevelApplication.dispatchEvent(new Event('Layer_Visible'));
if (hideLayer.alpha == 1){
hideLayer.alpha = .5;
}
else if (hideLayer.alpha == .5){
hideLayer.alpha = 1;
}
//trace("parameters are " + ObjectUtil.toString(data));
}
private function findSource():*{
if (data){
//iconType.source = "";
if (data.type == "Image"){
//trace("data.name: " + data.name);
//trace("data.bitmapinfo: " + data.bitmapinfo);
return new Bitmap(data.bitmapinfo);
}
if (data.type == "Text"){
return("assets/images/Text2.png");
}
if (data.type == "Application"){
return
//return("assets/images/App.png");
}
if (data.type == "Button"){
return("assets/images/Button.png");
}
if (data.type == "Shape"){
return("assets/images/shape.png");
}
if (data.type == "SWF"){
return("assets/images/SWF.png");
}
else{
return "assets/images/placeholder.png";
}
}
else {
return "assets/images/placeholder.png";
}
}
private function truncateName(nameStr:String):String
{
var returnVal:String = (nameStr.indexOf(".") > -1) ? nameStr.substr(0, nameStr.indexOf(".")) : nameStr;
var extension:String = (nameStr.indexOf(".") > -1) ? nameStr.substr(nameStr.indexOf("."),nameStr.length) : "";
//trace("nameStr: " + nameStr);
//trace("extension: " + extension);
if (returnVal.length > MAX_NAME_LENGTH){
returnVal = returnVal.substr(0,MAX_NAME_LENGTH) + "...";
}/*else{
returnVal += extension;
}*/
return returnVal;
}
]]>
</fx:Script>
<s:Group id="layerGroup" width="100%" height="100%" top="10" left="5" bottom="10" right="10">
<s:HGroup left="0" verticalAlign="middle" width="100%">
<s:HGroup paddingBottom="40" paddingRight="10">
<mx:Image id="iconType" smoothBitmapContent="true" scaleContent="true" source="" height="20" width="20"/>
</s:HGroup>
<s:HGroup width="100%">
<s:Label toolTip="{data.name}" text="{truncateName(data.name)}" id="labelText" height="50" top="5" width="100%" maxDisplayedLines="1" left="0" color="#101010"/>
<s:Label toolTip="" text="{Math.ceil(data.fileSize/1000)+' K'}" textAlign="right" id="sizeText" height="50" top="5" width="70" maxDisplayedLines="1" left="0" color="#101010"/>
</s:HGroup>
<s:HGroup paddingBottom="40">
<mx:Image horizontalAlign="right" bottom="10" alpha="1" right="2" id="hideLayer" verticalAlign="middle" source="assets/images/visible.png" click="hideLayers()" useHandCursor="true"/>
<mx:Image id="actLabel" includeInLayout="false" visible="{this.myvis}" source="assets/images/star.png" />
</s:HGroup>
</s:HGroup>
</s:Group>
</s:ItemRenderer>
Here is the class that uses said renderer:
<?xml version="1.0" encoding="utf-8"?>
<s:BorderContainer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
left="5" top="10" bottom="0"
creationComplete="init();" rollOver="rolledOver(event)" rollOut="rolledOut(event)"
backgroundColor="#F0F0F0" backgroundAlpha="1" borderAlpha="0" borderColor="#3a3a3a" width="100%" height="60" currentState="out">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:states>
<s:State name="over"/>
<s:State name="out" />
</s:states>
<fx:Script>
<![CDATA[
import components.*;
import components.AdCanvas;
import events.AdCanvasObjectEvent;
import flash.system.LoaderContext;
import mx.collections.ArrayCollection;
import mx.controls.Image;
import mx.core.Application;
import mx.core.DragSource;
import mx.core.FlexGlobals;
import mx.core.IUIComponent;
import mx.core.UIComponent;
import mx.events.DragEvent;
import mx.graphics.ImageSnapshot;
import mx.managers.DragManager;
import spark.components.Group;
import spark.layouts.*;
[Bindable]
private var _data: Object;
[Bindable]
private var context:LoaderContext;
[Bindable]
public var canvas: AdCanvas;
[Bindable]
public var index: int;
[Bindable]
public var maxPreviewWidth: int;
[Bindable]
public var maxPreviewHeight: int;
[Bindable]
public var isSelected: Boolean = false;
[Bindable]
private var adRect:Rectangle;
[Bindable]
private var ad:BitmapData;
[Bindable]
public var layerData:ArrayCollection = new ArrayCollection();
[Bindable]
private var application:Object = FlexGlobals.topLevelApplication;
//public var layerList:List;
private const MAX_HEIGHT:Number = 400;
private const MINIMUM_HEIGHT:Number = 60;
private var t:Timer;
private var t2:Timer;
private var t3:Timer;
[Bindable]private var siblings:Array = new Array();
/**
* Initialize the preview item
*/
public function init(obj: Object = null): void {
//layersList.data = FlexGlobals.topLevelApplication.getLayerList();
//trace("Layer data " + layersList.data);
canvas.screenPreview = this;
context = new LoaderContext(false);
FlexGlobals.topLevelApplication.addEventListener(AdCanvasObjectEvent.UPDATED, updateThumbnail);
FlexGlobals.topLevelApplication.addEventListener(AdCanvasObjectEvent.ADDED, updateThumbnail);
FlexGlobals.topLevelApplication.addEventListener(AdCanvasObjectEvent.DELETED, updateThumbnail);
FlexGlobals.topLevelApplication.addEventListener(AdCanvasObjectEvent.SELECTED_SINGLE, updateThumbnail);
FlexGlobals.topLevelApplication.addEventListener(AdCanvasObjectEvent.SELECTED_MULTIPLE, updateThumbnail);
FlexGlobals.topLevelApplication.addEventListener(AdCanvasObjectEvent.DESELECT, updateThumbnail);
FlexGlobals.topLevelApplication.addEventListener("updateThumbnail", updateThumbnail);
// This is to prevent the security error when there is a loaded swf trying to be accessed for bitmap
Security.loadPolicyFile(FlexGlobals.topLevelApplication.parameters.mediaUrl+"../crossdomain.xml");*/
//if(root.loaderInfo.url.indexOf('file://')==-1)img.loaderContext = new LoaderContext(true, ApplicationDomain.currentDomain, SecurityDomain.currentDomain);
canvas.updatePreview();
buildThumb();
titleBar.addEventListener(MouseEvent.CLICK, mouseClick);
(adCanvas.isDeletable || adCanvas.isDeletable == "true") ? screenDelete.addEventListener(MouseEvent.CLICK, mouseClick) : null;
//layersList.addEventListener(DragEvent.DRAG_ENTER, handleDragEnter);
//layersList.addEventListener(DragEvent.DRAG_DROP, handleDragDrop);
//layersList.addEventListener(DragEvent.DRAG_START, handleDragStart);
this.addEventListener(DragEvent.DRAG_ENTER, handleDragEnter);
this.addEventListener(DragEvent.DRAG_DROP, handleDragScreenDrop);
//setHeight();
//setYPos();
}
private function handleDragStart(event:DragEvent):void{
try{
var obj:Object = (event.dragInitiator as List).selectedItem;
canvas.selected = obj["object"];
}catch (error:Error){
trace("ERROR: ScreenPreview.mxml - handleDragStart() : " + error.message);
}
}
private function handleDragEnter(event:DragEvent):void {
trace("event.dragInitiator: " + event.dragInitiator);
if( event.dragInitiator is List){
DragManager.acceptDragDrop(this);
DragManager.showFeedback(DragManager.MOVE);
layersList.dropEnabled = true;
}else{
layersList.dropEnabled = false;
}
}
private function handleDragDrop(event:DragEvent):void {
t = new Timer(500);
t.addEventListener(TimerEvent.TIMER, checkLayerData);
t.start();
}
private function handleDragScreenDrop(event:DragEvent):void {
/*trace("\n");
trace("TEEEEE HEEEEEE");
trace("event.target: " + event.target);
trace("event.currentTarge: " + event.currentTarget);
trace("this: " + this);
trace("event.dragInitiator: " + (event.dragInitiator as List).selectedItem);
trace("event.draggedItem: " + event.draggedItem);
trace("event.dragSource: " + event.dragSource);
*/
try
{
var obj:Object = (event.dragInitiator as List).selectedItem;
var clone:UIComponent = obj["element"].clone();
/*for( var i:* in obj)
{
trace( "obj["+i+"]: " + obj[i]);
}
trace("obj: " + obj);
*/
this.canvas.addObjectToCanvas(clone);
obj["adCanvas"].removeScreenElement(obj);
}catch(error:Error){
trace("ERROR: ScreenPreview - handleDragDrop() : " + error.message);
}
//trace("\n");
}
private function checkLayerData(e:TimerEvent):void
{
t.stop();
t = null;
adCanvas.updateItemIndex();
}
public function setSizeText(val:Number):void
{
sizeText.text = (Math.ceil(val/1000) + " K");
if (isSelected)
{
t3 = new Timer(100);
t3.addEventListener(TimerEvent.TIMER, delayResize);
t3.start();
}
}
/**
* Update the bitmap data for the screen when something has changed.
*/
public function updateThumbnail(ev: AdCanvasObjectEvent = null): void {
try{
canvas.gridOff();
var adRect:Rectangle = canvas.adBox.getBounds(canvas);
var snapshot: BitmapData = ImageSnapshot.captureBitmapData((canvas as IBitmapDrawable));
var ad:BitmapData = new BitmapData(adRect.width, adRect.height);
ad.copyPixels(snapshot, adRect, new Point());
img.source = new Bitmap(ad);
canvas.gridOn();
}catch(e:Error){
trace(e+"System can't convert external swf files to bitmap.");
canvas.gridOn();
}
}
/**
* Controls visuals for when the button is selected.
*/
public function set selected(state: Boolean): void
{
isSelected = state;
trace("MY STATE IS: " + state);
if (isSelected)
{
layersList.includeInLayout=true;
stroke.color=0x878787;
strokeColor.color=0x878787;
bg.color = 0x979fa7;
layersList.visible = true;
//layersList.percentHeight = 100;
screenSettings.visible = true;
(adCanvas.isDeletable || adCanvas.isDeletable == "true") ? screenDelete.visible = true : screenDelete.visible = false;
//percentHeight=100;
siblings.splice(0,siblings.length);
siblings = new Array();
try
{
for(var i:int=0; i < Group(parent).numChildren; i++)
{
siblings.push(Group(parent).getElementAt(i));
}
}
catch (e:Error) {}
t2 = new Timer(100);
t2.addEventListener(TimerEvent.TIMER, delayResize);
t2.start();
}
else
{
stroke.color=0x3C3C3C;
strokeColor.color=0x3C3C3C;
bg.color = 0x636B73;
currentState="out";
layersList.includeInLayout=false;
}
}
private function delayResize(evt:TimerEvent):void{
if(t2){
t2.stop();
t2.removeEventListener(TimerEvent.TIMER, delayResize);
t2 = null;
}
if(t3){
t3.stop();
t3.removeEventListener(TimerEvent.TIMER, delayResize);
t3 = null;
}
setHeight();
setYPos();
}
public function setYPos():void
{
for(var i:int = 0; i < siblings.length; i++)
{
if(i>0)
{
siblings[i].y = ( siblings[i-1].y + siblings[i-1].height);
}
if (siblings[i] != this){
ScreenPreview(siblings[i]).selected = false;
ScreenPreview(siblings[i]).checkLayer();
}
}
}
public function setHeight():void
{
for(var i:int = 0; i < siblings.length; i++)
{
if( siblings[i] == this )
{
if( (MINIMUM_HEIGHT + totLayersHeight()) > MAX_HEIGHT){
height = MAX_HEIGHT;
}else{
height = MINIMUM_HEIGHT + totLayersHeight();
}
}
trace("###################################################");
trace("ScreenPreview - canvas: " + canvas);
trace("ScreenPreview - canvas.href: " + canvas.href);
trace("ScreenPreview - canvas.click_label: " + canvas.click_label);
trace("###################################################");
FlexGlobals.topLevelApplication.setMouseActionsFromObject();
}
}
private function totLayersHeight():Number{
trace("this.layerData.length: " + this.layerData.length);
var val:Number = 0;
//multiply by 40 because that is the height of each layer item
if( this.layerData.length > 0) val = (this.layerData.length + 1) * 40;
return val;
}
public function checkLayer ():void{
screenSettings.visible = false;
screenDelete.visible = false;
layersList.visible = false;
//percentHeight=15;
height = 60;
}
/**
* Controls visuals for when the button is rolled over.
*/
private function rolledOver(e:Event):void
{
str.color=0xffc423;
bg.color=0xBAC2CA;
}
/**
* Controls visuals for when the button is rolledout.
*/
private function rolledOut(e:Event):void{
if(!isSelected){
bg.color=0x636B73;
/*g1.color=0xCBCBCB;
g2.color=0xD9D9D9;
str.color=0xCBCBCB;
lg.rotation=-90;*/
}else{
bg.color=0x979fa7;
/*g1.color=0xCBCBCB;
g2.color=0xCBCBCB;
str.color=0xCBCBCB;
lg.rotation=90*/
}
}
/**
* Set up the canvas and SWF sizes, as well as label, for the screen thumbnail.
*/
public function buildThumb():void{
adRect = new Rectangle(15, 15, canvas.adBox.width, canvas.adBox.height);
ad = new BitmapData(adRect.width + 100, adRect.height + 100, true, 0);
setImageSize();
labelText.text = "Screen "+canvas.index;//+": "+canvas.adWidth+"x"+canvas.adHeight;
updateThumbnail();
}
/**
* Get the scaled-down screen size.
*/
private function getScaledDimensions(targetHeight:int=100, targetWidth:int=100): Object {
var xScaleFactor: Number = (maxPreviewWidth > targetWidth) ? (targetWidth/maxPreviewWidth) : 1;
var yScaleFactor: Number = (maxPreviewHeight > targetHeight) ? (targetHeight/maxPreviewHeight) : 1;
var scaleFactor: Number = (xScaleFactor < yScaleFactor) ? xScaleFactor : yScaleFactor;
var dimensions: Object = {
width: Math.round(adRect.width * scaleFactor),
height: Math.round(adRect.width * scaleFactor)
}
return dimensions;
}
/**
* Change the the thumb size and position based on the ad size.
*/
private function setImageSize():void
{
var w:Number = adRect.width + 100;
var h:Number = adRect.height + 100;
var scaler:Number = (w>h)?40/w:27/h;
img.width = w*scaler;
img.height = h*scaler;
rolledOut(null);
imgBox.left = 10;
if (w > (h*2)){
imgBox.top=15;
}
if (h > (w*2)){
imgBox.top = 5;
}
}
private function mouseClick(e:MouseEvent):void
{
trace("did the click");
e.stopImmediatePropagation();
if( e.currentTarget == screenDelete)
{
trace("DISPATCH DELETE SCREEN");
dispatchEvent(new Event('delete_screen_click'));
}else{
trace("DISPATCH MOUSE CLICK");
dispatchEvent(new Event('mouse_click'));
FlexGlobals.topLevelApplication.dispatchEvent(new AdCanvasObjectEvent(AdCanvasObjectEvent.DESELECT));
}
//FlexGlobals.topLevelApplication.updateLayerScreens();
}
private function deleteThisScreen(e:MouseEvent):void
{
dispatchEvent(new Event('delete_screen_click'));
}
/**
* Getter and setter for adcanvas that we are using for the thumbnail
*/
public function set adCanvas(canv: AdCanvas): void {
canvas = canv;
index = canv.index;
}
public function get adCanvas(): AdCanvas {
return canvas;
}
/**
* Getter for checking if this button has been selected.
*/
public function get selected(): Boolean {
return isSelected;
}
private function settingsMenu():void{
FlexGlobals.topLevelApplication.dispatchEvent(new AdCanvasObjectEvent(AdCanvasObjectEvent.DESELECT));
FlexGlobals.topLevelApplication.openSettings();
}
]]>
</fx:Script>
<s:VGroup left="1" right="1" top="1" height="100%" width="100%" paddingBottom="5">
<s:VGroup id="titleBar" height="55" top="20" width="100%">
<s:HGroup top="5" left="5" height="100%" width="100%">
<s:Group width="55" height="50">
<s:Rect id="fill" left="5" right="0" top="0" bottom="0" radiusX="0">
<s:fill>
<s:SolidColor id="bg" color="0x979fa7"/>
</s:fill>
<s:stroke>
<s:SolidColorStroke id="stroke" color="0x3C3C3C" alpha="1"/>
</s:stroke>
</s:Rect>
<s:HGroup id="vg" height="50" width="100%" gap="0">
<s:Group height="15" top="2" width="100%">
<s:VGroup top="5" id="imgBox" width="15">
<mx:Image left="5" id="img" scaleContent="true" height="50" width="50" top="10" />
</s:VGroup>
</s:Group>
</s:HGroup>
<s:Rect left="1" right="1" top="1" bottom="1" radiusX="0" >
<s:stroke>
<s:SolidColorStroke id="str" color="0x979fa7" weight="2" alpha="0" />
</s:stroke>
</s:Rect>
</s:Group>
<s:Group left="0" top="0" height="60" width="100%">
<s:Rect top="0" left="5" right="0" bottom="0" bottomLeftRadiusX="0" bottomRightRadiusX="0">
<s:fill>
<s:SolidColor id="bg2" color="0xDCE4EC" alpha="0"/>
</s:fill>
<s:stroke>
<s:SolidColorStroke id="strokeColor" color="0x3C3C3C" alpha="0"/>
</s:stroke>
</s:Rect>
<s:HGroup verticalAlign="middle" top="15" width="100%">
<mx:Text id="labelText" text="" selectable="false" color="#3a3a3a" width="100%" fontSize="10" textAlign="center" />
<mx:Text id="sizeText" text="" selectable="false" color="#3a3a3a" width="100%" fontSize="10" textAlign="right" />
</s:HGroup>
</s:Group>
<s:Group>
<mx:Image source="assets/images/trashcan-delete.png" visible="false" toolTip="Delete This Screen" id="screenDelete" top="15" right="45" useHandCursor="true"/>
<mx:Image source="assets/images/cog.png" visible="false" toolTip="Edit Screen Settings" top="15" right="11" id="screenSettings" click="settingsMenu()" useHandCursor="true"/>
</s:Group>
</s:HGroup>
</s:VGroup>
<s:VGroup id="layerPanel" includeInLayout="true" paddingBottom="1" height="100%" width="100%">
<s:List creationComplete="{trace('TEEEEEEEEEEEEE HEEEEEEEEEEEEEEE')}"
id="layersList"
dragStart="{handleDragStart(event)}" dragEnter="{handleDragEnter(event)}" dragDrop="{handleDragDrop(event)}"
dragEnabled="true"
dropEnabled="true"
dragMoveEnabled="true"
includeInLayout="true"
visible="true"
initialize="application.setUpLayers()"
dataProvider='{layerData}'
selectedIndex="{application.getLayerListIndex()}"
render='{layersList.selectedIndex=application.getLayerListIndex()}'
itemRenderer="renderers.LayerRenderer"
width="100%"
height="100%"
bottom="50"
alternatingItemColors="[#e2e2e2, #dedede]"
selectionColor="#787878"
rollOverColor="#949494"
borderVisible="false"
/>
</s:VGroup>
</s:VGroup>
</s:BorderContainer>
The problem I'm having is the itemRenderer never gets called. I put trace statements just to be sure and nothing. These two files once used mx:canvas and were converted. I've been beating my head against a wall for 2 days with this issue. Help is much appreciated.

Cannot correctly resize an image via action script

Hi I am trying to add an image when I click on a thumbnail.
I know I have to use a listener (Event.COMPLETE ?), but the image is not resizing correctly when I rotate the tablet.
I believe the problem is that I cannot resize the image within the addImage1() function, as the image has not yet loaded, but I cannot use newImg.width within the listener function to reset the image width.
Any help would be most appreciated.
Code follows:-)
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="ZOOM Pictues with Tap"
resize="view1_resizeHandler(event)">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.events.ResizeEvent;
public var hasImageBeenAdded:Boolean = false;
private var imageLastWidth:Number;
private var imageLastHeight:Number;
private var zoomFactor:Number;
private var imageNumber:Number;
private var rhsKeepWidth:int;
private var rhsKeepHeight:int;
private var rhsKeep:Boolean = false;
protected function view1_resizeHandler(event:ResizeEvent):void
{
if(rhsKeepWidth > rhsKeepHeight) // Was Landscape is now Portrait
{
var tmpWidth2:int = rhsKeepWidth;
var tmpHeight2:int = rhsKeepHeight;
rhsKeepWidth = tmpHeight2-lhs.width;
rhsKeepHeight = tmpWidth2+lhs.width;
}
else //Was Portrait is now Landscape
{
var tmpWidth1:int = rhsKeepWidth;
var tmpHeight1:int = rhsKeepHeight;
rhsKeepWidth = tmpHeight1-lhs.width;
rhsKeepHeight = tmpWidth1+lhs.width;
}
addImage1();
}
protected function removeAllImages():void
{
var totalElements : int = rhs.numElements;
for(var i:int=totalElements-1;i>=0;i--)
{
rhs.removeElementAt(i);
}
}
private function onImageLoaded(e:Event):void
{
var zoomFactor1:Number;
var zoomFactor2:Number;
imageLastWidth = e.target.sourceWidth;
imageLastHeight = e.target.sourceHeight;
if(rhsKeep != true) //Need to set the rhs VGroup dimensions
{
rhs.width = hGroup1.width-lhs.width;
rhs.height = hGroup1.height;
rhsKeep = true;
rhsKeepWidth = rhs.width;
rhsKeepHeight = rhs.height;
}
zoomFactor1 = rhsKeepWidth/imageLastWidth;
zoomFactor2 = rhsKeepHeight/imageLastHeight;
if(zoomFactor1 < zoomFactor2)
{
zoomFactor = zoomFactor1;
}
else
{
zoomFactor = zoomFactor2;
}
trace("zoomFactor=" + zoomFactor);
}
public function addImage1():void
{
var i:int;
var newImg:Image = new Image();
removeAllImages();
newImg.source = "images/1.jpg";
newImg.x = 0;
newImg.y = 0;
newImg.addEventListener(Event.COMPLETE,onImageLoaded);
rhs.addElementAt(newImg,0);
hasImageBeenAdded = true;
imageNumber = 1;
trace("Image Width= " + newImg.width);
newImg.scaleX = newImg.scaleY = zoomFactor;
}
]]>
</fx:Script>
<s:HGroup id="hGroup1" width="100%" height="100%">
<s:Scroller id="scrollerL" height="100%">
<s:VGroup id="lhs" width="15%" height="100%" gap="10"
horizontalAlign="center" verticalAlign="top">
<s:Image width="100" height="100" source="thumbs/1.jpg" click="addImage1()"/>
</s:VGroup>
</s:Scroller>
<s:Scroller id="scroller1" height="100%" width="100%">
<s:VGroup id="rhs" height="100%">
</s:VGroup>
</s:Scroller>
</s:HGroup>
</s:View>
Regarding the device orientation, you should use:
trace(Stage.deviceOrientation);
trace(Stage.orientation);
They are read-only strings outputting information regarding the device's and the screen's orientation. You may manually set the stage's orientation:
Stage.setOrientation(StageOrientation.DEFAULT);
Regarding the image loading, you need an eventListener for Event.COMPLETE and you should also cast the content as Image:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(event:Event):void {
trace("Image loaded");
// Handle code here
// Use: (loader.content as Image)
});
loader.load(new URLRequest("images/1.jpg"));