Jul 06
编辑页面CSS的时候,很多的时候都不知道图片中颜色的像素值,每次都要用Photoshop之类的工具打开,来获取像素值。Flex中继承了PhotoShop的这一方便的功能,通过Bitmap类,BitmapData类以及getPixel(),就可以简单的取得颜色值。接下来的例子就演示了Flex中利用Bitmap类,BitmapData类以及getPixel()事件,获取图片中颜色像素值。
让我们先来看一下Demo(可以右键View Source或点击这里察看源代码):
下面是完整代码(或点击这里察看):
Download: main.mxml
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
- layout="vertical"
- verticalAlign="middle"
- backgroundColor="white">
- <mx:Script>
- <![CDATA[
- private var bm:Bitmap;
- private var bmd:BitmapData;
- private function image_complete(evt:Event):void {
- /* Create Bitmap from Image content. */
- bm = img.content as Bitmap;
- /* Create new BitmapData object. */
- bmd = new BitmapData(img.contentWidth, img.contentHeight);
- /* Draw Bitmap into BitmapData. */
- bmd.draw(bm.bitmapData);
- }
- private function image_mouseMove(evt:MouseEvent):void {
- /* Get the pixel currently under the mouse cursor. */
- var color:int = bmd.getPixel(evt.localX, evt.localY);
- /* Convert the color value from a number to Hex string. */
- var colorStr:String = color.toString(16).toUpperCase();
- /* Set the swatch Box instance's backgroundColor style to the color under the mouse cursor. */
- swatch.setStyle("backgroundColor", color);
- /* Make sure colorStr is at least 6 characters. */
- colorStr = "000000" + colorStr;
- /* Make sure colorStr is at MOST 6 characters. */
- lbl.text = "#" + colorStr.substr(colorStr.length - 6);
- }
- ]]>
- </mx:Script>
- <mx:Zoom id="zoom" />
- <mx:VBox>
- <mx:Image id="img" source="image1.jpg" completeEffect="{zoom}" complete="image_complete(event);" mouseMove="image_mouseMove(event)" />
- <mx:HBox>
- <mx:Box id="swatch" width="{lbl.height}" height="{lbl.height}" />
- <mx:Label id="lbl" width="100" fontFamily="_typewriter" fontSize="16" />
- </mx:HBox>
- </mx:VBox>
- </mx:Application>
代码:Peter deHaan 翻译/整理/编译:minidxer
