Files
haxework/haxework/gui/utils/DrawUtil.hx
2014-02-28 17:07:02 +04:00

57 lines
1.8 KiB
Haxe
Executable File

package haxework.gui.utils;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.display.BitmapData;
import flash.display.Graphics;
@:fakeEnum(String) enum FillType {
NONE;
DEFAULT;
COVER;
CONTAIN;
REPEAT;
}
class DrawUtil {
public static function draw(graphics:Graphics, image:BitmapData, rect:Rectangle, ?fillType:FillType = null, ?color:Int = -1, ?clear:Bool = true):Void {
if (fillType == null) fillType = FillType.DEFAULT;
if (clear) graphics.clear();
if (color > -1) {
graphics.beginFill(color);
graphics.drawRect(rect.x, rect.y, rect.width, rect.height);
graphics.endFill();
}
var m:Matrix = new Matrix();
var s:Float = 1.0;
switch (fillType) {
case FillType.REPEAT:
graphics.beginBitmapFill(image, m, true, false);
graphics.drawRect(rect.x, rect.y, rect.width, rect.height);
graphics.endFill();
return;
case FillType.NONE:
graphics.beginBitmapFill(image, m, false, false);
graphics.drawRect(rect.x, rect.y, rect.width, rect.height);
graphics.endFill();
return;
case FillType.DEFAULT:
case FillType.CONTAIN:
s = Math.min(rect.width / image.width, rect.height / image.height);
case FillType.COVER:
s = Math.max(rect.width / image.width, rect.height / image.height);
}
m.scale(s, s);
var dx:Float = (rect.width - image.width * s) / 2;
var dy:Float = (rect.height - image.height * s) / 2;
m.translate(dx, dy);
graphics.beginBitmapFill(image, m, false, true);
rect.x = Math.max(rect.x, m.tx);
rect.y = Math.max(rect.y, m.ty);
rect.width = Math.min(rect.width, image.width * s);
rect.height = Math.min(rect.height, image.height * s);
graphics.drawRect(rect.x, rect.y, rect.width, rect.height);
graphics.endFill();
}
}