Drawing in Flex

I would like to "draw" simple shape like rectangle over an
loaded image inside Image component. I don't want to alter loaded
image, just to draw a rectangle for example over it with
possibility to later click and interact with it. I have no idea
where to start since i have no experience with drawing in Flex.
What would be the best way to do that? I would really appreciate it
if somene can point me in right direction.
thanks in advance

Hi,
The simplest is to create a custom MXML component and
override the updateDisplayList() method within Script tags. Then
you can use the ActionScript drawing API on the graphics object of
the component to draw whatever you fancy programmatically:
<?xml version="1.0" encoding="utf-8"?>
<mx:Image xmlns:mx="
http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import flash.display.*;
import flash.geom.*;
import flash.utils.*;
import mx.core.EdgeMetrics;
import mx.utils.ColorUtil;
import mx.utils.GraphicsUtil;
public var _gradientFrom:int;
public var _gradientTo:int;
public function set gradientFrom(value:int):void
this._gradientFrom = value;
public function set gradientTo(value:int):void
this._gradientTo = value;
override protected function
updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
super.updateDisplayList(unscaledWidth, unscaledHeight);
var g:Graphics = graphics;
var b:EdgeMetrics = borderMetrics;
var w:Number = unscaledWidth - b.left - b.right;
var h:Number = unscaledHeight - b.top - b.bottom;
var m:Matrix = verticalGradientMatrix(0, 0, w, h);
g.clear();
g.beginGradientFill("linear", [_gradientFrom, _gradientTo],
[1, 1], [0, 255], m);
var cn:uint = this.getStyle("cornerRadius");
GraphicsUtil.drawRoundRectComplex(g, b.left, b.top, w, h,
cn, cn, cn, cn);
g.endFill();
]]>
</mx:Script>
</mx:Image>

Similar Messages

  • Free hand drawing in Flex

    I want to create a application which provide free hand drawing to user.
    After drawing if shape has close borders user should be able to fill it.
    Any body have idea how to proceed?

    You are mixing AWT (Canvas) and Swing (JFrame, JPanel etc). Is is a NO NO. Either all AWT or ALL Swing but not a mixture. When using Swing you can normally replace Canvas with either JPanel or JComponent and do your drawing in the painyComponent(Graphics g) method.

  • How to draw a hollow ring in flex

    i gotta requirement to draw a ring in my project... currentlty am drawing a circle with border and decreased alpha value.... it pretend to be a ring but it is not...... here is my code:
                                   var spr:Sprite = event.target.parent as Sprite;
                                    s = new Sprite();
                                    s.graphics.clear();
                                    s.graphics.lineStyle(5, 0xFF0000);                               
                                    s.graphics.beginFill(0xffffff);//d9d9d9  0xfbfbfb
                                    s.alpha=0.4;
                                    s.graphics.drawCircle(spr.mouseX,spr.mouseY,10);
                                    s.graphics.endFill();
                                    img.addChild(s);
                                    addChild(img);
    any one hepl me out plz

    Hi,
    The following code is just a basic ring you could do things like mouse events etc and they will only respond to the ring itself as the 'group' has the mouseenabledwheretransparent set to false.
    The width of the ring is controlled by the stroke weight
    MyRing.mxml - you can use as a component or just use copy the group into your application
    <?xml version="1.0" encoding="utf-8"?>
    <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx" width="300" height="300" mouseEnabledWhereTransparent="false">
    <s:Ellipse top="0" left="0" bottom="0" right="0">
    <s:stroke>
    <s:SolidColorStroke color="0x000000" weight="20"/>
    </s:stroke>
    </s:Ellipse>
    </s:Group>
    David

  • Errors - drawing a text curve in flex with flex 3 with flex 3.5 framework

    Is that necessary in drawing a text curve in flex we need flex 4 with flash player 10, actually i have flex 3 with flex 3.5 framework but it is showing error like this :
    This is my code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.components.TextView;
    public var myText:String = "Read my blog @ http://www.funnyjokesfunny.com";
    var radius:Number = 125;
    var spacing:Number = 8;    
    var center:Point = new Point(125,125);
    public function drawText():void {
    for (var char:uint=0;char<myText.length;char++) {
    var tempText:TextView = new TextView();
    tempText.x = radius * Math.cos(degrees2radians(char*spacing)) + center.x;
    tempText.y = radius * Math.sin(degrees2radians(char*spacing)) + center.y;
    tempText.rotation = 25;
    tempText.text = myText.charAt(char);
    textContainer.addChild(tempText);
    ]]>
    </mx:Script>
    <mx:Button label="Draw a circle" click="drawText()" />
    <mx:Canvas id="textContainer"  y="50" x="50"  width="400" height="400" />       
    </mx:Application>
    1) call to possibly  undefined method Text View
    2) Type was not found : Text view.                               
    Please help me
    Atishay

    I have now taken import mx.controls.Text;
    instead of textview it works , but in dis example http://blog.shortfusion.com/index.cfm/2009/1/25/Circular-Text-In-Flex-Explained with source code they have taken textview control and it works for them for text curve.

  • Error #2123 bitmap.draw à partir d'un flux HDS dans une application Flex

    Bonjour à tous,
    Je suis en train de développer un player vidéo en Flex qui doit prendre en charge le HDS.
    J'essaie en vain depuis hier de créer une une image Bitmap à partir d'un flux HDS que je récupère d'Akamai.
    J'ai essayer avec un Flux RTMP, aucun problème, j'arrive bien à créer une image bitmap à partir du flux vidéo. Mais dès  que j'essaie avec un flux HDS, j'ai une erreur # 2123 qui correspond à une violation de sécurité.
    le message complet :
    Error #2123: Violation de la sécurité Sandbox : BitmapData.draw : http://192.168.0.194/test-hds/testHDS.swf ne peut pas accéder à null. Accès refusé à tous les fichiers de régulation.
    J'ai créer un serveur avec Wowza en version trial pour avoir un exemple de flux HDS. Même problème qu'avec le flux d'Akamai
    Mon Code :
    Fichier testHDS.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                    xmlns:mx="library://ns.adobe.com/flex/mx"
                    xmlns:s="library://ns.adobe.com/flex/spark"
                    minWidth="955" minHeight="800" creationComplete="init()" layout="absolute">
            <!-- Placer ici les éléments non visuels (services et objets de valeur, par exemple). -->
        <fx:Declarations>
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                import mx.controls.Alert;
                import mx.core.FlexGlobals;
                import mx.core.UIComponent;
                private var osmfPlayer:OSMFPlayer;
                public function init():void{         
                    Security.allowDomain("*")
                    Security.loadPolicyFile("http://192.168.0.194/crossdomain.xml");              
                    osmfPlayer = new OSMFPlayer();
                    this.addChild(osmfPlayer);
                protected function myBtn_clickHandler(event:MouseEvent):void
                    try {
                        var dpo:DisplayObject = osmfPlayer.player.displayObject;      
                        var imgBD:BitmapData;
                        var imgBitmap:Bitmap;
                        imgBD = new BitmapData(100,100);
                        imgBD.draw(osmfPlayer.player.displayObject as DisplayObject);
                        imgBitmap=new Bitmap(imgBD);              
                        var comp :UIComponent = new UIComponent();
                        comp.addChild(imgBitmap);
                        comp.x =0  ;
                        comp.y = 720;
                        addChild(comp);
                        Alert.show("ok");              
                    catch(e:Error){
                        Alert.show(e.message);
            ]]>
        </fx:Script>
        <s:Button id="myBtn" x="0" y="720" label="MyButton" click="myBtn_clickHandler(event)">      
        </s:Button>
    </mx:Application>
    Fichier OSMFPlayer.as
    package
        import mx.core.UIComponent;
        import org.osmf.containers.MediaContainer;
        import org.osmf.media.DefaultMediaFactory;
        import org.osmf.media.MediaElement;
        import org.osmf.media.MediaPlayer;
        import org.osmf.media.URLResource;
        public class OSMFPlayer extends UIComponent
            //URI of the media
            public static const PROGRESSIVE_PATH:String =
                "http://192.168.0.194:1935/vod/mp4:sample.mp4/manifest.f4m";       
            public var player:MediaPlayer;
            public var container:MediaContainer;
            public var mediaFactory:DefaultMediaFactory;  
            public function OSMFPlayer()
                initPlayer();
            protected function initPlayer():void
                //the pointer to the media
                var resource:URLResource = new URLResource( PROGRESSIVE_PATH );
                // Create a mediafactory instance
                mediaFactory = new DefaultMediaFactory();      
                //creates and sets the MediaElement (generic) with a resource and path
                var element:MediaElement = mediaFactory.createMediaElement( resource );
                //the simplified api controller for media
                player = new MediaPlayer( element );
                //the container (sprite) for managing display and layout
                container = new MediaContainer();
                container.addMediaElement( element );
                //Fit the player size
                container.width =  1280;
                container.height = 720 ;//- FlexGlobals.topLevelApplication.actionBar.height;
                //Adds the container to the stage
                this.addChild( container );
    crossdomain.xml
    Emplacement :  à la racine du serveur
    <?xml version="1.0"?>
    <cross-domain-policy>
    <site-control permitted-cross-domain-policies="master-only" />
    <allow-access-from domain="*" />
    <allow-access-from domain="*.adobe.com" />
    <allow-access-from domain="*.macromedia.com" />
    </cross-domain-policy>
    //fin de code
    J'ai d'abord pensé que c'était lié au crossdomain.xml, j'en ai testé un certains nombre, ca ne change rien.
    Je ne sais plus trop quoi faire
    Si quelqu'un avait une idée ou une piste, je suis à cours !
    Merci d'avance

    Perhaps if you are going to use a foreign language in your post, you should use it in the title, also, so as otherw will know what to expect... you will be more likely to get responses from those who speak the same language also... not a criticism, just a suggestion. and no need to repost again...

  • Draw circles,images in flex

    How can we draw circles,images in flex? (ex as in
    ms-paint)

    http://livedocs.adobe.com/flex/3/html/help.html?content=Drawing_Vector_Graphics_1.html

  • Draw a rectangle from a flex app

    Hello,
    GRAND CHALLENGE (should be "hello world" that anyone should
    easily find):
    1) - a flex app with a button
    2) - when clicked the button draw the rectangle
    PROPOSED NON WORKING SOLUTION:
    draw.mxml:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:Script>import DrawApp;</mx:Script>
    <mx:Script>
    <![CDATA[
    function drawNow():void{
    var myRectangle:DrawApp = new DrawApp();
    myCanvas.addChild(myRectangle.returnRectangle());
    ]]>
    </mx:Script>
    <mx:Canvas width="100%" height="100%"
    id="myCanvas"></mx:Canvas>
    <mx:Button label="draw"
    click="drawNow()"></mx:Button>
    </mx:Application>
    DrawApp.as:
    // ActionScript file
    package {
    import flash.display.*;
    class DrawApp extends Sprite
    public function DrawApp()
    //don't use the constructor anymore since it won't return
    the rectangle
    public function returnRectangle():Shape
    var rectAndCircle:Shape=new Shape();
    rectAndCircle.graphics.lineStyle(1);
    rectAndCircle.graphics.beginFill(0x0000FF,1);
    rectAndCircle.graphics.drawRect(125,0,550,575);
    rectAndCircle.graphics.endFill();
    return rectAndCircle;
    }//class
    }//package
    I've got an error "1034" (BTW as a bonus if anyone know how i
    can avoid to have the localized AS3 error messages so I can paste
    full error messages in English)
    CHALLENGE:
    Can someone show me how to make this wok before Silverlight2
    Beta get out?
    Thanks from francois who's mad trying to solve this "should
    be obvious hello world" for too long and who also discovered
    lately:
    - the lack of threads in AS3
    - the insane security policy around Flash Player (must
    install a proxy to access a public API...)
    - etc.
    Help please Oo

    Ok found the solution: needed to change the "Shape" object by
    a "UIComponent" object (don't know why).

  • Drawing different geometric shapes in flex

    Hi
    Can I know how to draw different geometric shapes(like square, polygon,rhombus) in flex and I should be able to calculate its x,y co-ordinates...
    Let me know if any examples are there...
    Thanks n Regards
    Aruna.S.N.

    Rob
    1. The Shapes menu is on the toolbar.
    Pull down the menu and choose the pentagon shape. That has a sliding controller that lets you choose the number of sides.
    2. 30°? which is +option shift 8+
    Peter

  • Draw a tail in Flex

    Hi,
         I need to draw a tail and this tail should look like a tail in all positions ie ('bottom','bottomRight','bottomLeft','top','topRight','topLeft'). Anybody know how to do it.
    Thanks & Regards,
    Jayagopal.

    u need to write a custom actionscript  class for this. U should draw the tail using drawing classes in flex. then u can customize the positions according to your requirement
    mark this answered if useful

  • How to Draw a vertical line in flex

    I was just wondering the simplest way to draw a vertical line , preferably dashed.

    You could always just use the graphics class of your chart component.  Just access its graphics object, set the line style/thickness, move to the start point, and line to the end point.  Something like this,
    this.graphics.lineStyle(1, 0x000000);
    this.graphics.moveTo(startX, startY);
    this.graphics.lineTo(endX, endY);

  • Drawing dashed line or dotted line in a flex line chart

    Friends,
    I want to draw a line chart which should be either dotted or dashed.
    since there is no component like dashed line chart, can anyone help me in creating one.
    i think if i extend the line series component, then i can draw that.
    but am stuck there. pls help people.
    Regards,
    Anoop

    Try looking [url http://www.macdevcenter.com/pub/a/mac/2002/03/22/vertical_text.html]here.
    : jay

  • Draw Line With Arrow between containers in flex

    I need to connect multiple containers by drawing arrow . can any one provide me the idea how to do?
    Thanks in Advance,
    senthil
    [email protected]

    If your containers are within a spark container them self then you could use fxg to draw arrows based on the containers boundaries
    eg this code will draw a red arrow:
    <Graphic xmlns="http://ns.adobe.com/fxg/2008" version="2"> <!-- Use Use compact syntax with absolute coordinates. --> <Path data=" M 20 0 C 50 0 50 35 20 35 L 15 35 L 15 45 L 0 32 L 15 19 L 15 29 L 20 29 C 44 29 44 6 20 6"> <!-- Define the border color of the arrow. --> <stroke> <SolidColorStroke color="#888888"/> </stroke> <!-- Define the fill for the arrow. --> <fill> <LinearGradient rotation="90"> <GradientEntry color="#000000" alpha="0.8"/> <GradientEntry color="#FFFFFF" alpha="0.8"/> </LinearGradient> </fill> </Path> </Graphic>
    you will have to scale the arrow according to your needs

  • Other Components Drawing Dashed Lines doesn't compile with Flex 4

    The lib was created in 2006 so it doesn't compile with Flex 4.
    The lib can be downloaded here http://www.quietlyscheming.com/blog/charts/dashed-lines/
    When compiling I get this error:
    Description     Resource     Path     Location     Type
    1136: Incorrect number of arguments.  Expected 3.     GraphicsUtils.as     /arrows/src/qs/utils     line 66     Flex Problem
    The line which doesn't compile:
    stroke.apply(target);
    How do I fix this error?

    I managed to compile the lib by rewriting the line:
    stroke.apply(target, new Rectangle(), new Point());
    But I don't understand what I have done.
    All Rectangle and Point dimensions are 0, but I'm sure it shouldn't be this way.

  • Is there any way to delay flex from drawing anything until everything is ready to be rendered?

    I have this CustomVideoPlayer which uses a skinned VideoPlayer and a button for closing. The problem I see is that when going out of fullscreen mode I can litterally see how the subcomponents of the videoPlayer - background frame etc shrinks and repositions in the middle of the screen cause I have vertical and horizontalCenter and etc. So whiching between both states is not fluent. I don't want to animate it, I just want not to see the glitching resizing and repostioning.
    So how can I "wait" till all elements are resized and repositioned in the normal state and then show the new state all at once with no glitching? Is it possible ?
    And one more extra question:
    I've taken a look inside the VideoPlayer class and I've noticed that when adding skin part for example PlayButton, they add a listener for Click, when they remove the part they remove it. That's ok but as component is removed from it's parent partRemoved is not called so the listener is never removed and would this make the component stuck in memory cause of that listener?
    Oh and one more small extra question:
    If a skin part is required does this also mean that it must exist in all states?
    (cause if it does that would mean I could add it's event listeners in the creation complete or partAdded, but not partRemoved function, since it would never be removed...)

    If I do this then I will have my video player in fullscreen disappear for a moment and then reappear out of fullscreen, and I want it not to disappear, but to just jump to the other state fully resized and repositioned with no glitching in between states.
    Than you will need to implement your own solution which meets your specific design goals. That's the nature of the beast my friend.
    As far as I know dynimic skin parts have another meaning - creating more than one instance at runtime. Also I've read just now (again) partAdded and partRemoved are called on component initialization and skin change. So basicly if I change the skin, it makes sense to remove the eventListeners from the old skin parts. But still, I've read on many places that if an object has event listeners attached to it it will Not be GC unless they are weak, so it will be stuck in memory forever.
    So looking at the VideoPlayer and it's skin parts, I'm not seeing any event listener being removed when I remove the instance I have of the VideoPlayer. Why is that? Why the component does not remove it's skin parts event listeners?
    Are you changing skins? If so, I bet the parts would be removed as expected. The partRemoved method is not being called because it's not needed. If you remove the parent component, than any reference encapuslated within that component are removed as well.Fire up the profiler if you don't believe me.
    I'm interested in the skin parts and states relation. With includeIn and excludeFrom you define in which states the component is added to or removed from as a child (element). So If I have a skin part which is required=true and I have 2 states from one of which it is excluded... whouldn't that result in a runtime error since the part is not there but it is required?
    I'm pretty sure that it only checks if the instance exists, and does not care if it has been created and added to the display list. I do not really know for certain though. This could easily be answered with a simple test.

  • How does Flex decide when to draw a scrollbar?

    First my problem...
    I have a tree whose data changes because I changed the contents of a custom object in the data provider's array collection. The scrollbar does not update itself when the tree expands beyond the view of the canvas. It doesn't update until I close the branch and then reopen it. Then, the scrollbar updates itself.
    What I've tried...
    So far, I figure that since the changes are occurring deep within the data provider, no Collection Event is getting dispatched. Since the structure is so..
    dataProvider = arrayCollection;
    arrayCollection[ 0 ] = parentNode : TreeNode;
    parentNode.children = ... // array collection of other TreeNodes
    So I've tried dispatching my own event when the addition of the nodes is through using the following...
    layerDirectoryArr.refresh(); // layerDirectory is the first child in the array collection in the dataProvider (parentNode)
    sidePanel.directoryTree.invalidateDisplayList();
    sidePanel.directoryTree.invalidateSize();
    layerDirectoryArr.dispatchEvent(new CollectionEvent(CollectionEventKind.UPDATE, false, false, CollectionEventKind.UPDATE, 0, 0, [layerDirectoryArr[0]]));
    I've also tried adding buttons to invalidateDisplayList(), invalidateSize() for the tree and neither work.
    More explanation on the code below..
    The data provider is an array collection of custom object that all have a "children" field (array collection) of the same custom objects. I have a Tree that is within a canvas. The Tree uses a custom renderer. The tree sits in the same position as a List. I use a "useTree" var to toggle the visibility, essentially to choose either the List or the Tree to be displayed within the Canvas. I set both of them at 0,0.
    <mx:Canvas width="100%"
                   id="hBox"
                   backgroundAlpha="0.7"
                   height="80%"
                   verticalScrollPolicy="off"
                   horizontalScrollPolicy="off"
                   backgroundColor="0x55FF66"
                   dataChange="validateNow()">
            <mx:List id="list"
                     width="100%"
                     height="100%"
                     labelField="name"
                     x="0"
                     y="0"
                     visible="{!useTree}"
                     backgroundAlpha="0.8"
                     itemRenderer="components.tree.CustomListItemRenderer"
                     creationComplete="listComplete(event)"
                     dataChange="validateNow()"/>
            <mx:Tree id="tree"
                     width="100%"
                     labelField="name"
                     showRoot="false"
                     visible="{useTree}"
                     backgroundAlpha="0.8"
                     x="0"
                     y="0"
                     creationComplete="treeComplete(event)"
                     dataProvider="{treeDataProvider}"
                     itemRenderer="{treeClass}"
                     valid="logTreeEvent(event)"
                     change="logTreeEvent(event)"
                     variableRowHeight="false">
            </mx:Tree>
        </mx:Canvas>

    If the Tree showed the new nodes, then notification is probably working.
    But showing new nodes may not force the tree to compute a new
    measuredHeight.  The container will check the measuredHeight and determine a
    desired height and show scrollbars if it doesn't fit.  If the container also
    has %height, it will not show scrollbars unless minHeight is set to a
    smaller number.

Maybe you are looking for

  • Material Availability date differs in R/3 & APO

    Hi, We are facing Issue with Material Avaialbility date for Planner order/Manufacturing Order in R/3 and APO. We are using a Master Recipe for PDS Creation in APO which consists on 9-10 different operations, out of which only inbetween operation 4-5-

  • EBS check out is not getting cleared? Explained Clearly.

    Hi Experts, while uploading BAI file into SAP, system is creating the following entry. Debit Bank Check-out clearing account Credit Main Bank Account Now the problem is, it's not offsetting the amount which is sitting in the Bank Check-Out Clearing A

  • How to best add VoiceOver accessibility for children's graphic books?

    iBooks Author seems fairly intuitive for the most part with the exception of adding accessibility (VoiceOver) for children's graphic books. My story is written as a rhyme and prefer the story to be heard as initial (or primary) VoiceOver after each p

  • Computer trying to install software.

    Every time I reboot, my computer tries to install "Solution Center" software that is already installed, and the update file is no longer even on my hard drive. So it can't find the installation file it tries to access. This just started happening out

  • Integration Directory - Cache Notifications

    I just installed QA box. I am trying to move my Integration Directory objects. When I do cache notifications in ID I get an error in the cache notifications Integration Server (ABAP Cache). Any help is appreciated.