## Draw dashed — line in Flash

/** * @description – returns a sprite with a dashed line * @langversion 3.0 * @usage drawDashedLine( 30, 30, 100, 100, 5, 3 ); * * @param graphicsObject The object where to draw the line * @param startX Start X of dashed line * @param startY Start Y of dashed line * @param endX End X of dashed line * @param endY End Y of dashed line * @param strokeLength Stroke length of dash * @param gap Length of gap between dashes * * @return sprite containing the dashed line */ import flash.display.Graphics; import flash.display.Sprite; function drawDashedLine( startX:Number=0, startY:Number=0, endX:Number=0, endY:Number=0, strokeLength:int=0, gap:int=0 ):Sprite { var line:Sprite = new Sprite(); var lineGraphics:Graphics = line.graphics; lineGraphics.lineStyle( 1, 0x000000, 1.0 ); //lineGraphics.lineTo( startX, startY ); // calculate the length of the segment var segmentLength:Number = strokeLength + gap; // calculate the length of the dashed line var deltaX:Number = endX - startX; var deltaY:Number = endY - startY; //By Pythagorous theorem var _delta:Number = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY)); // calculate the number of segments needed var segmentsCount:Number = Math.floor(Math.abs( _delta / segmentLength )); // get the angle of the line in radians var radians:Number = Math.atan2( deltaY, deltaX ); // start the line here var aX:Number = startX; var aY:Number = startY; // add these to cx, cy to get next seg start deltaX = Math.cos( radians ) * segmentLength; deltaY = Math.sin( radians ) * segmentLength; // loop through each segment for (var i:int = 0; i < segmentsCount; i++) { lineGraphics.moveTo( aX, aY ); lineGraphics.lineTo( aX + Math.cos( radians ) * strokeLength, aY + Math.sin( radians ) * strokeLength ); aX += deltaX; aY += deltaY; } // handling the last segment lineGraphics.moveTo( aX, aY ); _delta = Math.sqrt( ( endX - aX ) * ( endX - aX ) + ( endY - aY ) * ( endY - aY ) ); if( _delta > segmentLength ){ // segment ends in the gap; drawing a full dash lineGraphics.lineTo( aX + Math.cos( radians ) * strokeLength, aY + Math.sin( radians ) * strokeLength ); } else if( _delta > 0 ) { // segment shorter than dash; draw the remaining only lineGraphics.lineTo( aX + Math.cos( radians ) * _delta, aY + Math.sin( radians ) * _delta ); } // move to the end position lineGraphics.lineTo( endX, endY ); return line; } addChild( drawDashedLine( 30, 30, 100, 100, 5, 3 ) );

Advertisements

i am trying the code but it shows error please can you help me? i need to draw dashed lines with flash

marioApril 18, 2011 at 9:58 PM

Hello mario duarte,

Actually due to bad formatting you got the errors, I have formatted it well now. Hope it helps you now.

Warm Regards

DD

Deepanjan DasApril 18, 2011 at 11:17 PM