In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

Bresenhamの直線描画アルゴリズム

クリックで再描画
Get Adobe Flash player
by _ueueueueue 06 May 2010
/**
 * Copyright _ueueueueue ( http://wonderfl.net/user/_ueueueueue )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/phii
 */

/*
* クリックで再描画
*/
package 
{
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	import flash.text.*;
	import flash.ui.*;
	
	[SWF(width=465,height=465,backgroundColor=0xFFFFFF)]
	
	/**
	 * ...
	 * @author ue
	 */
	
	public class Main extends Sprite 
	{
		private var pointA:SimplePoint;
		private var pointB:SimplePoint;
		private var canvas:BitmapData;
		
		public function Main():void 
		{
			canvas = new BitmapData(465, 465, false, 0x0);
			addChild(new Bitmap(canvas));
			
			pointA = new SimplePoint(100, 100);
			pointB = new SimplePoint(200, 300);
			
			draw(pointA, pointB);
			
			stage.addEventListener(MouseEvent.CLICK, onClick);
		}
		
		private function onClick(e:MouseEvent):void 
		{
			pointA.x = Math.random() * stage.stageWidth;
			pointA.y = Math.random() * stage.stageHeight;
			pointB.x = Math.random() * stage.stageWidth;
			pointB.y = Math.random() * stage.stageHeight;
			
			draw(pointA,pointB);
		}

		private function draw(p1:SimplePoint,p2:SimplePoint,color:uint = 0xFFFFFF):void
		{
			canvas.fillRect(canvas.rect, 0x0);
			canvas.lock();
			
			var xx:int = p1.x;
			var yy:int = p1.y;
			var dx:int = (p2.x - p1.x < 0) ? (p2.x - p1.x) * -1 : p2.x - p1.x;
			var dy:int = (p2.y - p1.y < 0) ? (p2.y - p1.y) * -1 : p2.y - p1.y;
			var sx:int = (p2.x > p1.x)? 1 : -1;
			var sy:int = (p2.y > p1.y)? 1 : -1;
			
			trace(dx, dy);
			
			if (dx >= dy)
			{
				var err:int = 2 * dy - dx;
				var i:int;
				for (i = 0; i <= dx; i++)
				{
					canvas.setPixel(xx, yy, color);
					xx += sx;
					err += 2 * dy;
					if (err >= 0)
					{
						yy += sy;
						err -= 2 * dx;
					}
				}
			}
			else
			{
				err = 2 * dx - dy;
				for (i = 0; i <= dy; i++)
				{
					canvas.setPixel(xx, yy, color);
					yy += sy;
					err += 2 * dx;
					if (err >= 0)
					{
						xx += sx;
						err -= 2 * dy;
					}
				}
			}
			
			canvas.unlock();
		}
	}
}

class SimplePoint
{
	private var _x:int;
	private var _y:int;
	public function SimplePoint(x:int,y:int)
	{
		_x = x;
		_y = y;
	}
	
	public function get x():int { return _x; }
	
	public function set x(value:int):void 
	{
		_x = value;
	}
	
	public function get y():int { return _y; }
	
	public function set y(value:int):void 
	{
		_y = value;
	}
}