第三讲   Android 位图操作 <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Bitmap Android 系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。对 Android 用户界面的设计,和对于 Android UI 开发自绘控件和游戏制作而言掌握好位图基础是必不可少的。本次主要涉及以下的相关内容。本文从应用的角度,着重介绍怎么用 Bitmap 来实现这些功能。

一、位图主要操作步骤

(一)获取图片

1 . 通过 BitmapDrawable 方式得到 Bitmap

InputStream is = res.openRawResource(R.drawable.picture);

BitmapDrawable bmpDraw = new BitmapDrawable(is);

Bitmap bmp = bmpDraw.getBitmap();

BitmapDrawable bmpDraw = (BitmapDrawable)res.getDrawable(R.drawable.picture);

/* 从资源文件中装载图片 */

       //getResources()->得到Resources

       //getDrawable()->得到资源中的Drawable对象,参数为资源索引ID

       //getBitmap()->得到Bitmap

mBitQQ = ((BitmapDrawable) getResources().getDrawable (R.drawable. qq )).getBitmap();

Bitmap bmp = bmpDraw.getBitmap();

2 . 通过 BitmapFactory 得到 Bitmap

Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.picture);

BitmapFactory 可以通过资源 ID 、路径、文件、数据流等方式来获取位图。

Android 可支持的图片格式如下: png jpg gif bmp

    // 从资源文件中装载图片   getResources()-> 得到 Resources

    //BitmapFactory 可以通过图像文件来获取位图

       mBitmapTop = BitmapFactory.decodeResource(getResources(), R.drawable. desktop );

 

  3 )用 createBitmap(w,h, Config.ARGB_8888) 得到屏幕上指定区域的位图

        int w = 240,h = 120;

       String mstrTitle = " 感受 Android 带给我们的新体验 " ;

        mbmpTest = Bitmap.createBitmap(w,h, Config. ARGB_8888 );

       Canvas canvasTemp = new Canvas( mbmpTest );

       canvasTemp.drawColor(Color. WHITE );

       Paint p = new Paint();

       String familyName = " 宋体 " ;

       Typeface font = Typeface.create(familyName,Typeface. BOLD );

       p.setColor(Color. RED );

       p.setTypeface(font);

       p.setTextSize(17);

       canvasTemp.drawText(mstrTitle,0,30,p);

       p.setColor(Color. YELLOW );

       canvasTemp.drawRect(100,40,200,110, p);

      

      

       canvas.drawBitmap( mbmpTest , 0, 180, null );      

      

(二)位图显示

Bitmap 显示到画布上:

1 )通过 Canvas 画布 drawbitmap 到屏幕上

  /* 在屏幕 (left,top) 处开始显示图片 bitmap */

     canvas.drawbitmap(Bitmap bitmap, float left, float top, Paint paint);

2 )通过 BitmapDrawable 绘制该图片到控件上   

//bitmap.draw(canvas);

转换为 BitmapDrawable 对象显示位图

        // 获取位图
        Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic180);
        //
转换为 BitmapDrawable 对象
        BitmapDrawable bmpDraw=new BitmapDrawable(bmp);
        //
显示位图
        ImageView iv2 = (ImageView)findViewById(R.id.ImageView02);
       iv2.setImageDrawable(bmpDraw);

 

(三)位图缩放

1 )重画位图

drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)

2 )缩放原位图,创建一个新的位图

createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)

3 scale  Canvas scale(float sx, float sy)

不过要注意此时整个画布都缩放了

4 )用 Matrix 实现位图缩放

Matrix matrix=new Matrix();

matrix.postScale(<?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />0.2f, 0.2f);

Bitmap bmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,t rue);

位图旋转 Matrix 实现

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);

Matrix matrix=new Matrix();

matrix.postRotate(45);

Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true);

canvas.drawColor(Color.BLACK);

二、位图主要概念

  android.content.res 资源类
  android.graphics 
底层图形类
 ( ) android.content.res.Resources

   对于 Android 平台的资源类 android.content.res.Resources 可能很多网友比较陌生,一起来看看 SDK 上是怎么介绍的吧, Contains classes for accessing application resources, such as raw asset files, colors, drawables, media or other other files in the package, plus important device configuration details (orientation, input types, etc.) that affect how the application may behave. 平时用到的二进制源文件 raw 、颜色 colors 、图形 drawables 和多媒体文件 media 的相关资源均通过该类来管理。

  int  getColor(int id)  对应 res/values/colors.xml

  Drawable  getDrawable(int id)  对应 res/drawable/

  XmlResourceParser  getLayout(int id)  对应 res/layout/

  String  getString(int id) CharSequence  getText(int id)   对应 res/values/strings.xml

  InputStream  openRawResource(int id)  对应 res/raw/

  void parseBundleExtra (String tagName, AttributeSet attrs, Bundle outBundle) 对应 res/xml/

  String[]  getStringArray(int id)  res/values/arrays.xml

  float  getDimension(int id)  res/values/dimens.xml

 ( )android.graphics.Bitmap

  作为位图操作类, Bitmap 提供了很多实用的方法,常用的我们总结如下 :
  boolean  compress(Bitmap.CompressFormat format, int quality, OutputStream stream)
压缩一个 Bitmap 对象根据相关的编码、画质保存到一个 OutputStream 中。其中第一个压缩格式目前有 JPG PNG
  void  copyPixelsFromBuffer(Buffer src)
从一个 Buffer 缓冲区复制位图像素
  void  copyPixelsToBuffer(Buffer dst) 
将当前位图像素内容复制到一个 Buffer 缓冲区

  我们看到创建位图对象 createBitmap 包含了 6 种方法在目前的 Android 2.1 SDK 中,当然他们使用的是 API Level 均为 1 ,所以说从 Android 1.0 SDK 开始就支持了,所以大家可以放心使用。

  static Bitmap  createBitmap(Bitmap src)
 static Bitmap  createBitmap(int[] colors, int width, int height, Bitmap.Config config)
 static Bitmap  createBitmap(int[] colors, int offset, int stride, int width, int height, Bitmap.Config config)
 static Bitmap  createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)
 static Bitmap  createBitmap(int width, int height, Bitmap.Config config)
 static Bitmap  createBitmap(Bitmap source, int x, int y, int width, int height)
 static Bitmap  createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)  //
创建一个可以缩放的位图对象

 final int  getHeight()  获取高度
 final int  getWidth()  
获取宽度
 final boolean  hasAlpha()  
是否有透明通道
 void  setPixel(int x, int y, int color)  
设置某像素的颜色
 int  getPixel(int x, int y) 
获取某像素的颜色, android 开发网提示这里返回的 int 型是 color 的定义

( ) android.graphics.BitmapFactory

Bitmap 实现在 Android.graphics 包中。但是 Bitmap 类的构造函数是私有的,外面并不能实例化,只能是通过 JNI 实例化。这必然是某个辅助类提供了创建 Bitmap 的接口,而这个类的实现通过 JNI 接口来实例化 Bitmap 的,这个类就是 BitmapFactory  

      作为 Bitmap 对象的 I/O 类, BitmapFactory 类提供了丰富的构造 Bitmap 对象的方法,比如从一个字节数组、文件系统、资源 ID 、以及输入流中来创建一个 Bitmap 对象,下面本类的全部成员,除了 decodeFileDescriptor 外其他的重载方法都很常用。

static Bitmap  decodeByteArray(byte[] data, int offset, int length) // 从字节数组创建

static Bitmap  decodeByteArray(byte[] data, int offset, int length, BitmapFactory.Options opts)

static Bitmap  decodeFile(String pathName, BitmapFactory.Options opts) // 从文件创建,路径要写全

static Bitmap  decodeFile(String pathName)

static Bitmap  decodeFileDescriptor(FileDescriptor fd, Rect outPadding, BitmapFactory.Options opts)  // 从输入流句柄创建

static Bitmap  decodeFileDescriptor(FileDescriptor fd)

static Bitmap  decodeResource(Resources res, int id)  // Android APK 文件资源中创建, android123 提示是从 /res/ drawable

static Bitmap  decodeResource(Resources res, int id, BitmapFactory.Options opts)

static Bitmap  decodeResourceStream(Resources res, TypedValue value, InputStream is, Rect pad, BitmapFactory.Options opts)

static Bitmap  decodeStream(InputStream is)  // 从一个输入流中创建

static Bitmap  decodeStream(InputStream is, Rect outPadding, BitmapFactory.Options opts)

 ( ) android.graphics.Canvas

  J2ME MIDLET 时我们就知道 Java 提供了 Canvas 类,而目前在 Android 平台中,它主要任务为管理绘制过程, The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).

    该类主要提供了三种构造方法,分别为构造一个空的 Canvas 、从 Bitmap 中构造和从 GL 对象中创建,如下

Canvas()
Canvas(Bitmap bitmap)
Canvas(GL gl)

  同时 Canvas 类的一些字段保存着重要的绘制方法定义,比如 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG 保存时需要 alpha 层,对于 Canvas 类提供的方法很多,每个都很重要,下面我们一一作介绍

void  concat(Matrix matrix)

void  drawARGB(int a, int r, int g, int b)
void  drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)

void  drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint)
void  drawBitmap(int[] colors, int offset, int stride, float x, float y, int width, int height, boolean hasAlpha, Paint paint)
void  drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)
void  drawBitmap(Bitmap bitmap, float left, float top, Paint paint)
void  drawBitmap(int[] colors, int offset, int stride, int x, int y, int width, int height, boolean hasAlpha, Paint paint)
void  drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint)
void  drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight, float[] verts, int vertOffset, int[] colors, int colorOffset, Paint paint)

void  drawCircle(float cx, float cy, float radius, Paint paint)
void  drawColor(int color)
void  drawColor(int color, PorterDuff.Mode mode)

 ( ) android.graphics.Matrix

利用 Bitmap Matrix 实现图像变换:剪切、旋转、缩放等操作。

<?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" />
 

用源 Bitmap 通过变换生成新的 Bitmap 的方法:

public static Bitmap createBitmap(Bitmap source, int x, int y, intwidth, int height,  

            Matrix m, boolean filter)  

public static Bitmap createBitmap(Bitmap source, int x, int y, intwidth, int height)  

public static Bitmap createScaledBitmap(Bitmap src, int dstWidth,  

            int dstHeight,boolean filter) 

第一个方法是最终的实现,后两种只是对第一种方法的封装。

 

第二个方法可以从源 Bitmap 中指定区域 (x,y, width, height) 中挖出一块来实现剪切;第三个方法可以把源 Bitmap 缩放为 dstWidth x dstHeight Bitmap

 

设置 Matrix Rotate (通过 setRotate() )或者 Scale (通过 setScale() ),传入第一个方法,可实现旋转或缩放。

原文链接: http://www.linuxidc.com/Linux/2011-09/43349p2.htm 

有关图形的变换、缩放等相关操作常用的方法有 :

  void  reset() // 重置一个 matrix 对象。

  void  set(Matrix src) // 复制一个源矩阵,和本类的构造方法 Matrix(Matrix src)  一样

  boolean  isIdentity() // 返回这个矩阵是否定义 ( 已经有意义 )

  void setRotate(float degrees) // 指定一个角度以 0,0 为坐标进行旋转

  void  setRotate(float degrees, float px, float py)  // 指定一个角度以 px,py 为坐标进行旋转

  void  setScale(float sx, float sy)  // 缩放

  void  setScale(float sx, float sy, float px, float py)  // 以坐标 px,py 进行缩放

  void setTranslate(float dx, float dy) // 平移

 void setSkew (float kx, float ky, float px, float py) // 以坐标 px,py 进行倾斜

 void setSkew (float kx, float ky) // 倾斜