Flex4 - 在一个区域内自由拖拽移动图片,缩放图片大小
如果图片过大,一般我们展示的时候要允许用户通过鼠标滚轮进行缩放,同时点击可以拖拽移动(类似百度地图那样的操作)。下面通过一个样例进行演示:


效果图如下:


代码如下:
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" backgroundColor="0x404040" creationComplete="init(event)"> <fx:Script> <![CDATA[ import mx.events.FlexEvent; //图片缩放比例 private var _imgScale:Number = 1; //图片坐标 private var _imgX:Number = 0; private var _imgY:Number = 0; /** * 设置监听 */ protected function init(event:FlexEvent):void { img.addEventListener(MouseEvent.MOUSE_DOWN, itemMouseDown); img.addEventListener(MouseEvent.MOUSE_UP, itemMouseUp); img.addEventListener(MouseEvent.ROLL_OUT, itemMouseUp); img.addEventListener(MouseEvent.MOUSE_WHEEL, itemMouseWheel); } /** * 鼠标按下开始拖动 */ private function itemMouseDown(event:MouseEvent = null):void{ var width:int = img.parent.width - img.width*_imgScale; var height:int = img.parent.height - img.height*_imgScale; img.startDrag(false, new Rectangle(0, 0 , width, height)); } /** * 鼠标弹起停止 拖动 */ private function itemMouseUp(event:MouseEvent):void{ img.stopDrag(); } /** * 鼠标滚轮控制缩放 */ private function itemMouseWheel(event:MouseEvent):void{ //计算每次的缩放比例 _imgScale = this.img.scaleX + (Math.abs(event.delta)/event.delta)*0.05; //设置最大最小的缩放限度 _imgScale = Math.min(1,_imgScale); var minScale:Number = Math.min(img.parent.width/img.width,img.parent.height/img.height); _imgScale = Math.max(minScale,_imgScale); //计算缩放后图片的坐标(保证缩放中心是鼠标) var oldScale:Number = this.img.scaleX; _imgX = this.img.x-(_imgScale/oldScale-1)*(this.img.parent.mouseX - this.img.x); _imgY = this.img.y-(_imgScale/oldScale-1)*(this.img.parent.mouseY - this.img.y); //坐标修正 if(img.width*_imgScale >= img.parent.width){ if(_imgX>=0){ _imgX=0; }else if((img.width*_imgScale+_imgX)<img.parent.width){ _imgX=img.parent.width-img.width*_imgScale; } } if(img.height*_imgScale >= img.parent.height){ if(_imgY>=0){ _imgY=0; }else if((img.height*_imgScale+_imgY)<img.parent.height){ _imgY=img.parent.height-img.height*_imgScale; } } //设置图片缩放比例和坐标 this.img.scaleX=_imgScale; this.img.scaleY=_imgScale; this.img.x = _imgX; this.img.y = _imgY; } ]]> </fx:Script> <s:Group clipAndEnableScrolling="true" width="70%" height="70%" horizontalCenter="0" verticalCenter="0"> <s:Rect width="100%" height="100%"> <s:fill> <s:SolidColor color="0xffffff"/> </s:fill> </s:Rect> <s:Image id="img" source="img.jpg"/> </s:Group> </s:Application>
赞一个