当前位置: > > > Flex3 - 自定义组件实现背景图片平铺

Flex3 - 自定义组件实现背景图片平铺

如果我们有一个自定义的组件需要平铺背景,只需重写updateDisplayList()方法即可。下面以一个继承Container的容器组件为例,可实现背景图片平铺,仅横向平铺,仅纵向平铺,图片拉伸。(如果背景图片有透明部分也可支持)
package
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import mx.core.Container;

	public class StepPage2 extends Container
	{
		/**
		 * 页面背景图
		 */
		[Embed(source="page_bg.png")]
		private static const PAGE_BG_CLASS:Class;
		
		/**
		 * 绘制对象和/或设置其子项的大小和位置
		 */
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
			var bitmapData:BitmapData = (new PAGE_BG_CLASS() as Bitmap).bitmapData;
			expandImage(bitmapData,unscaledWidth,unscaledHeight); //全部平铺
			//expandImage(bitmapData,unscaledWidth,bitmapData.height); //横向平铺
			//expandImage(bitmapData,bitmapData.width,unscaledHeight); //纵向平铺
			//expandImage(bitmapData,unscaledWidth,unscaledHeight,false); //背景图拉伸
		}
		
		private function expandImage(source:BitmapData, w:uint, h:uint,
									 repeat:Boolean=true, smooth:Boolean=false):BitmapData{
			var scaleMatrix:Matrix;
			var bd:BitmapData;
			graphics.clear();
			if (w == 0){
				w = 1;
			};
			if (h == 0){
				h = 1;
			};
			bd = new BitmapData(w, h, true, 0);
			if (!(repeat)){
				scaleMatrix = new Matrix();
				scaleMatrix.scale((w / source.width), (h / source.height));
			};
			graphics.beginBitmapFill(source, scaleMatrix, repeat);
			graphics.drawRect(0, 0, w, h);
			bd.draw(this, new Matrix());
			return (bd);
		}
	} 
}
评论0