Jul 06

编辑页面CSS的时候,很多的时候都不知道图片中颜色的像素值,每次都要用Photoshop之类的工具打开,来获取像素值。Flex中继承了PhotoShop的这一方便的功能,通过Bitmap类,BitmapData类以及getPixel(),就可以简单的取得颜色值。接下来的例子就演示了Flex中利用Bitmap类,BitmapData类以及getPixel()事件,获取图片中颜色像素值。

让我们先来看一下Demo(可以右键View Source或点击这里察看源代码):


下面是完整代码(或点击这里察看):

Download: main.mxml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
  3.         layout="vertical"
  4.         verticalAlign="middle"
  5.         backgroundColor="white">
  6.  
  7.     <mx:Script>
  8.         <![CDATA[
  9.             private var bm:Bitmap;
  10.             private var bmd:BitmapData;
  11.  
  12.             private function image_complete(evt:Event):void {
  13.                 /* Create Bitmap from Image content. */
  14.                 bm = img.content as Bitmap;
  15.  
  16.                 /* Create new BitmapData object. */
  17.                 bmd = new BitmapData(img.contentWidth, img.contentHeight);
  18.  
  19.                 /* Draw Bitmap into BitmapData. */
  20.                 bmd.draw(bm.bitmapData);
  21.             }
  22.  
  23.             private function image_mouseMove(evt:MouseEvent):void {
  24.                 /* Get the pixel currently under the mouse cursor. */
  25.                 var color:int = bmd.getPixel(evt.localX, evt.localY);
  26.  
  27.                 /* Convert the color value from a number to Hex string. */
  28.                 var colorStr:String = color.toString(16).toUpperCase();
  29.  
  30.                 /* Set the swatch Box instance's backgroundColor style to the color under the mouse cursor. */
  31.                 swatch.setStyle("backgroundColor", color);
  32.  
  33.                 /* Make sure colorStr is at least 6 characters. */
  34.                 colorStr = "000000" + colorStr;
  35.  
  36.                 /* Make sure colorStr is at MOST 6 characters. */
  37.                 lbl.text = "#" + colorStr.substr(colorStr.length - 6);
  38.             }
  39.         ]]>
  40.     </mx:Script>
  41.  
  42.     <mx:Zoom id="zoom" />
  43.  
  44.     <mx:VBox>
  45.         <mx:Image id="img" source="image1.jpg" completeEffect="{zoom}" complete="image_complete(event);" mouseMove="image_mouseMove(event)" />
  46.  
  47.         <mx:HBox>
  48.             <mx:Box id="swatch" width="{lbl.height}" height="{lbl.height}" />
  49.             <mx:Label id="lbl" width="100" fontFamily="_typewriter" fontSize="16" />
  50.         </mx:HBox>
  51.     </mx:VBox>
  52.  
  53. </mx:Application>
代码:Peter deHaan 翻译/整理/编译:minidxer

written by Minidxer  |  tags: , , , ,

One Response to “Flex中利用Bitmap类,BitmapData类以及getPixel()事件获取图片中颜色像素值的例子”

Trackbacks

Leave a Reply