Flex预览图片并让其自动适用容器大小

最近找了一下让图片 自动适应容器的例子,网上也有;但是有些不是很理想。其实说白了 就是让容器的大小跟图片的真实大小,

进行比值针对各种情况进行处理图片的大小,对图片按照一定的比值进行缩放。下面是我整理的例子,希望对遇到这个问题的同志有帮助。

下面是示例代码:

<?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"  creationComplete="init()" >
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <fx:Script>
        <![CDATA[
            import flash.display.Sprite;
            import flash.events.*;
            import flash.net.FileFilter;
            import flash.net.FileReference;
            import flash.net.URLRequest;
            import mx.controls.Alert;
            import mx.controls.Image;
            import mx.events.EffectEvent;
            
            
            private var fileReference:FileReference;
            private var byteArray:ByteArray;   
            private var bitmapData:BitmapData;   
            private var loader:Loader; 
            private var winDIVTitle:String = "图片加载至内存显示预览";
            
            public function init():void 
            {
                fileReference = new FileReference();
                loader = new Loader(); 
                configureListeners(fileReference);
            }
            
            private function configureListeners(dispatcher:IEventDispatcher):void {
                dispatcher.addEventListener(Event.CANCEL, cancelHandler);
                dispatcher.addEventListener(Event.COMPLETE, completeHandler);
                dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
                dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
                dispatcher.addEventListener(Event.OPEN, openHandler);
                dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
                dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
                dispatcher.addEventListener(Event.SELECT, selectHandler);
                dispatcher.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadCompleteDataHandler);
            }
            
            private function getTypes():Array {
                var allTypes:Array = new Array(getImageTypeFilter());
                return allTypes;
            }
            
            private function getImageTypeFilter():FileFilter {
                return new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png");
            }
        
            
            private function cancelHandler(event:Event):void {
                trace("cancelHandler: " + event);
            }
            
            /***
             * 文件选择完成之后
             * */
            private function completeHandler(event:Event):void
            {
                trace("completeHandler: " + event);
                byteArray = fileReference.data;   
                loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loaderCompleteHandler);   
                loader.loadBytes(byteArray);   
            }
            
            private function loaderCompleteHandler(e:Event):void   
            {   
                var bitmap:Bitmap = Bitmap(loader.content);   
                bitmapData = bitmap.bitmapData;
                img.source = new Bitmap(bitmapData,"auto",true); ; 
                /***矫正图片 让图片自动适应容器***/
                imgLoadFinish(e);
            }   
            
            private function uploadCompleteDataHandler(event:DataEvent):void {
                trace("uploadCompleteData: " + event);
                img.addEventListener(Event.COMPLETE, imgLoadFinish);
                
            }
            
            private function httpStatusHandler(event:HTTPStatusEvent):void {
                trace("httpStatusHandler: " + event);
            }
            
            private function ioErrorHandler(event:IOErrorEvent):void {
                trace("ioErrorHandler: " + event);
            }
            
            private function openHandler(event:Event):void {
                trace("openHandler: " + event);
            }
            
            private function progressHandler(event:ProgressEvent):void {
                var file:FileReference = FileReference(event.target);
                trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
            }
            
            private function securityErrorHandler(event:SecurityErrorEvent):void {
                trace("securityErrorHandler: " + event);
            }
            
            private function selectHandler(event:Event):void {
                var file:FileReference = FileReference(event.target);
                trace("selectHandler: name=" + file.name);
                //file.upload(uploadURL);
                /**将文件加载至内存,预览出来**/
                fileReference.load();
            }

            private function btnClick():void   
            {   
                fileReference.browse(getTypes());
            }   
            
            
            private function imgLoadFinish(evt:Event):void
            {
                //原始图片的大小   --- 第一次加载的时候这种方法获取不到图片的真实大小
                //var real_width:Number = img.contentWidth ;
                //var real_height:Number = img.contentHeight;
                
                var real_width:Number = evt.currentTarget.content.width;
                var real_height:Number = evt.currentTarget.content.height;
                //容器的大小
                var flashWidth:Number = divMain.width;
                var flashHeight:Number = divMain.height;
                
                //Alert.show("图片源文件大小:"+ real_width +" * " +real_height + "\n" 
// + "容器大小: " + flashWidth +" * " +flashHeight,"容器、图片尺寸信息" );
//比值 var w_bi:Number = real_width/width; var h_bi:Number = real_height/height; if(w_bi < 1 && h_bi <1) { //第一次也不行 不能真正获取到真实大小 //img.width = img.content.width; //img.height = img.content.height; img.width = evt.currentTarget.content.width; img.height = evt.currentTarget.content.height; //Alert.show("img大小:"+ img.content.width +" * " + img.content.height + "\n" + "evt大小: "
// + evt.currentTarget.content.width +" * " + evt.currentTarget.content.height,"w_bi < 1 && h_bi <1" );
//Alert.show("图片宽高都比容器小"); } else { if(w_bi > h_bi) { img.width = flashWidth; img.height = real_height * flashWidth / real_width; //Alert.show("w_bi > h_bi" + img.width + "* " + img.height); } else { img.height = flashHeight; img.width = real_width * flashHeight / real_height; //Alert.show("w_bi < h_bi" + img.width + "* " + img.height); } } img.x = (flashWidth - img.width) / 2; img.y = (flashHeight - img.height) / 2; fileInfo.text = fileReference.name + "源文件大小( "+ real_width +" * " +real_height+")"; } ]]> </fx:Script> <s:Panel x="151" y="41" width="574" height="410" id="winDIV" title="{winDIVTitle}" horizontalCenter="0" verticalCenter="0" > <mx:Canvas x="10" y="10" width="552" height="323" id="divMain" horizontalScrollPolicy="off" verticalScrollPolicy="off"> <mx:Image id="img" horizontalAlign="center" verticalAlign="middle" /> </mx:Canvas> <s:Button x="480" y="341" label="浏览文件" id="scan" height="30" width="83" click="btnClick()"/> <s:Label x="10" y="341" width="451" height="26" id="fileInfo" verticalAlign="middle"/> </s:Panel> </s:Application>

注:FileReference只有Flex4.0++版本才有data属性跟load方法,跟AS3有点区别。有了这个裁剪图片之间就不需要先将图片上传至服务器了,直接在内存中操作,

裁剪好之后再上传至服务器。(这个挺好的);例子代码 基本是API的示例代码

最后附上加载大图小图的效果:

大图片:

小图片:


posted @ 2012-05-29 09:09  Ajava攻城师  阅读(1108)  评论(0编辑  收藏  举报
无觅关联推荐,快速提升流量