第三讲  Android位图操作
BitmapAndroid系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。对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 可支持的图片格式如下:pngjpggifbmp
    //从资源文件中装载图片  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)
3scale  Canvas scale(float sx, float sy)
不过要注意此时整个画布都缩放了
4)用Matrix实现位图缩放
Matrix matrix=new Matrix();
matrix.postScale(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中。其中第一个压缩格式目前有JPGPNG
  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)  //AndroidAPK文件资源中创建,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
利用BitmapMatrix实现图像变换:剪切、旋转、缩放等操作。
 
用源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 dstHeightBitmap
 
设置MatrixRotate(通过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) //倾斜