Android技术精髓-Bitmap详解

来源:互联网 发布:insar数据购买 编辑:程序博客网 时间:2024/05/22 04:56

Bitmap (android.graphics.Bitmap)

Bitmap是Android系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。 
Bitmap类:

public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream) 压缩:

将位图的压缩到指定的OutputStream。如果返回true,位图可以通过传递一个相应的InputStream BitmapFactory.decodeStream(重建)。 format: 压缩图像的格式 quality: 0-100。 0含义压缩为小尺寸,100压缩的意思为最大质量。(PNG是无损的,会忽略品质设定 ) stream: OutputStream中写入压缩数据。 return: 是否成功压缩到指定的流。 

public void recycle()——回收位图占用的内存空间,把位图标记为Dead 
public final boolean isRecycled() ——判断位图内存是否已释放 
public final int getWidth()——获取位图的宽度 
public final int getHeight()——获取位图的高度 
public final boolean isMutable()——图片是否可修改 
public int getScaledWidth(Canvas canvas)——获取指定密度转换后的图像的宽度 
public int getScaledHeight(Canvas canvas)——获取指定密度转换后的图像的高度 
public boolean compress(CompressFormat format, int quality, OutputStreamstream)——按指定的图片格式以及画质,将图片转换为输出流。 
format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG 
quality:画质,0-100.0表示最低画质压缩,100以最高画质压缩。对于PNG等无损格式的图片,会忽略此项设置。 
常用的静态方法: 
public staticBitmap createBitmap(Bitmap src) ——以src为原图生成不可变得新图像 public staticBitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)——以src为原图,创建新的图像,指定新图像的高宽以及是否变。 public staticBitmap createBitmap(int width, int height, Config config)——创建指定格式、大小的位图 public staticBitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source为原图,创建新的图片,指定起始坐标以及新图像的高宽。 public staticBitmap createBitmap(Bitmap source, int x, int y, int width, int height, Matrixm, boolean filter) 

BitmapFactory工厂类: 
Option 参数类: public boolean inJustDecodeBounds——如果设置为true,不获取图片,不分配内存,但会返回图片的高宽度信息。 
public int inSampleSize——图片缩放的倍数。如果设为4,则宽和高都为原来的1/4,则图是原来的1/16。 
public int outWidth——获取图片的宽度值 
public int outHeight——获取图片的高度值 
public int inDensity——用于位图的像素压缩比 
public int inTargetDensity——用于目标位图的像素压缩比(要生成的位图) 
public boolean inScaled——设置为true时进行图片压缩,从inDensity到inTargetDensity。 读取一个文件路径得到一个位图。如果指定文件为空或者不能解码成文件,则返回NULL。 
public staticBitmap decodeFile(String pathName, Options opts) 
public staticBitmap decodeFile(String pathName) 读取一个资源文件得到一个位图。如果位图数据不能被解码,或者opts参数只请求大小信息时,则返回NuLL。(即当Options.inJustDecodeBounds=true,只请求图片的大小信息。) 
public staticBitmap decodeResource(Resources res, int id) public staticBitmap decodeResource(Resources res, int id, Options opts) 
从输入流中解码位图 public static Bitmap decodeStream(InputStreamis) 
从字节数组中解码生成不可变的位图 public staticBitmap decodeByteArray(byte[] data, int offset, int length) 
BitmapDrawable类: 继承于Drawable,你可以从文件路径、输入流、XML文件以及Bitmap中创建。 
常用的构造函数: Resourcesres=getResources();//获取资源 
publicBitmapDrawable(Resources res)——创建一个空的drawable。(Response用来指定初始时所用的像素密度)替代public BitmapDrawable()方法(此方法不处理像素密度) 
publicBitmapDrawable(Resources res, Bitmap bitmap)——从位图创建绘制 
publicBitmapDrawable(Resources res, String filepath)——通过打开agiven文件路径和位图解码创建绘制 
publicBitmapDrawable(Resources res, java.io.InputStream is)——创建一个可绘制从给定的输入流bydecoding位图。 


使用BitmapFactory解码资源


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
importandroid.app.Activity;
importandroid.graphics.BitmapFactory;
importandroid.graphics.drawable.Drawable;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.widget.ImageView;
 
publicclass Test extendsActivity {
      @Override
      publicvoid onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          ImageView imgView = (ImageView)findViewById(R.id.image3);
           
          imgView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.icon) );
      }
}

//main.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!--?xml version="1.0"encoding="utf-8"?-->
 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent">
  <linearlayout android:orientation="vertical"android:layout_width="wrap_content"android:layout_height="fill_parent">
 
  <imageview android:id="@+id/image1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/icon">
 
  <imageview android:id="@+id/image2"android:layout_width="125dip"android:layout_height="25dip"android:src="#555555">
  </imageview></imageview></linearlayout>
  <linearlayout android:orientation="vertical"android:layout_width="wrap_content"android:layout_height="fill_parent">
 
  <imageview android:id="@+id/image3"android:layout_width="wrap_content"android:layout_height="wrap_content">
 
  <imageview android:id="@+id/image4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/icon"android:scaletype="centerInside"android:maxwidth="35dip"android:maxheight="50dip">
 
  </imageview></imageview></linearlayout>
</linearlayout>
捕获和保存位图

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
importjava.io.File;
 
importandroid.app.Activity;
importandroid.content.ContentValues;
importandroid.content.Intent;
importandroid.content.pm.ActivityInfo;
importandroid.graphics.Bitmap;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.provider.MediaStore;
importandroid.provider.MediaStore.Images.Media;
importandroid.util.Log;
importandroid.view.View;
 
publicclass Test extendsActivity {
  Uri myPicture = null;
    @Override
    publicvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
    publicvoid captureImage(View view)
    {
        Intent i = newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(i,0);
    }
    @Override
    protectedvoid onActivityResult(intrequestCode, intresultCode, Intent data) {
        if(requestCode==0&& resultCode==Activity.RESULT_OK)
        {
             Bitmap myBitmap = (Bitmap) data.getExtras().get("data");
        }
    }
}


位图大小

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
importjava.io.File;
 
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.view.Display;
importandroid.widget.ImageView;
 
publicclass Test extendsActivity {
  finalstatic int CAMERA_RESULT = 0;
  ImageView imv;
  String imageFilePath;
  @Override
  publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/a.jpg";
    File imageFile = newFile(imageFilePath);
    Uri imageFileUri = Uri.fromFile(imageFile);
    Intent i = newIntent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
    startActivityForResult(i, CAMERA_RESULT);
  }
 
  protectedvoid onActivityResult(intrequestCode, intresultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if(resultCode == RESULT_OK) {
      imv = (ImageView) findViewById(R.id.ReturnedImageView);
      Display currentDisplay = getWindowManager().getDefaultDisplay();
      BitmapFactory.Options bmpFactoryOptions = newBitmapFactory.Options();
      bmpFactoryOptions.inJustDecodeBounds = true;
      Bitmap bmp = BitmapFactory.decodeFile(imageFilePath,
          bmpFactoryOptions);
 
      bmpFactoryOptions.inSampleSize = 2;
      bmpFactoryOptions.inJustDecodeBounds = false;
      bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
      imv.setImageBitmap(bmp);
    }
  }
}

//layout/main.xml
?
1
2
3
4
<!--?xml version="1.0"encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent">
  <imageview android:id="@+id/ReturnedImageView"android:layout_width="wrap_content"android:layout_height="wrap_content"></imageview>
</linearlayout>


在画布(Canvas)上绘制位图

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
importjava.io.FileNotFoundException;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.graphics.Canvas;
importandroid.graphics.Paint;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.ImageView;
 
publicclass Test extendsActivity implementsOnClickListener {
  ImageView chosenImageView;
  Button choosePicture;
  @Override
  publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView);
    choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton);
 
    choosePicture.setOnClickListener(this);
  }
 
  publicvoid onClick(View v) {
    Intent choosePictureIntent = newIntent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent,0);
  }
 
  protectedvoid onActivityResult(intrequestCode, intresultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
 
    if(resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();
      try{
        BitmapFactory.Options bmpFactoryOptions = newBitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri),null, bmpFactoryOptions);
        bmpFactoryOptions.inSampleSize = 2;
 
        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri),null, bmpFactoryOptions);
        Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
            .getHeight(), bmp.getConfig());
        Canvas canvas = newCanvas(alteredBitmap);
        Paint paint = newPaint();
        canvas.drawBitmap(bmp,0,0, paint);
        ImageView alteredImageView = (ImageView) this
            .findViewById(R.id.AlteredImageView);
        alteredImageView.setImageBitmap(alteredBitmap);
        chosenImageView.setImageBitmap(bmp);
      }catch(FileNotFoundException e) {
        Log.v("ERROR", e.toString());
      }
    }
  }
}

//main.xml
?
1
2
3
4
5
6
7
<!--?xml version="1.0"encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent">
<button android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Choose Picture" android:id="@+id/ChoosePictureButton">
 
<imageview android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/ChosenImageView"></imageview>
<imageview android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/AlteredImageView"></imageview>
</button></linearlayout>




Bitmap.createBitmap
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
importjava.io.FileNotFoundException;
 
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.graphics.Canvas;
importandroid.graphics.Paint;
importandroid.graphics.PorterDuffXfermode;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.Display;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.ImageView;
 
publicclass Test extendsActivity implementsOnClickListener {
  Button choosePicture1, choosePicture2;
  ImageView compositeImageView;
  Bitmap bmp1, bmp2;
  Canvas canvas;
  Paint paint;
 
  @Override
  publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    compositeImageView = (ImageView) this
        .findViewById(R.id.CompositeImageView);
 
    choosePicture1 = (Button) this.findViewById(R.id.ChoosePictureButton1);
    choosePicture2 = (Button) this.findViewById(R.id.ChoosePictureButton2);
 
    choosePicture1.setOnClickListener(this);
    choosePicture2.setOnClickListener(this);
  }
 
  publicvoid onClick(View v) {
    Intent choosePictureIntent = newIntent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent,1);
  }
 
  protectedvoid onActivityResult(intrequestCode, intresultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
 
    if(resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();
      bmp1 = loadBitmap(imageFileUri);
      Bitmap drawingBitmap = Bitmap.createBitmap(bmp1.getWidth(),
          bmp1.getHeight(), bmp1.getConfig());
      canvas = newCanvas(drawingBitmap);
      paint = newPaint();
      canvas.drawBitmap(bmp1,0,0, paint);
      paint.setXfermode(newPorterDuffXfermode(
          android.graphics.PorterDuff.Mode.MULTIPLY));
      canvas.drawBitmap(bmp2,0,0, paint);
      compositeImageView.setImageBitmap(drawingBitmap);
    }
  }
 
  privateBitmap loadBitmap(Uri imageFileUri) {
    Display currentDisplay = getWindowManager().getDefaultDisplay();
 
    floatdw = currentDisplay.getWidth();
    floatdh = currentDisplay.getHeight();
 
    Bitmap returnBmp = Bitmap.createBitmap((int) dw, (int) dh,
        Bitmap.Config.ARGB_4444);
    try{
      BitmapFactory.Options bmpFactoryOptions = newBitmapFactory.Options();
      bmpFactoryOptions.inJustDecodeBounds = true;
      returnBmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri),null, bmpFactoryOptions);
      bmpFactoryOptions.inSampleSize = 2;
      bmpFactoryOptions.inJustDecodeBounds = false;
      returnBmp = BitmapFactory.decodeStream(getContentResolver()
          .openInputStream(imageFileUri),null, bmpFactoryOptions);
    }catch(Exception e) {
      Log.v("ERROR", e.toString());
    }
    returnreturnBmp;
  }
}


在画布上绘制位图(使用矩阵)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
importjava.io.FileNotFoundException;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.graphics.Canvas;
importandroid.graphics.Matrix;
importandroid.graphics.Paint;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.Display;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.ImageView;
 
publicclass Test extendsActivity implementsOnClickListener {
 
  ImageView chosenImageView;
  Button choosePicture;
 
  @Override
  publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView);
    choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton);
 
    choosePicture.setOnClickListener(this);
  }
 
  publicvoid onClick(View v) {
    Intent choosePictureIntent = newIntent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent,0);
  }
 
  protectedvoid onActivityResult(intrequestCode, intresultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
 
    if(resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();
 
      Display currentDisplay = getWindowManager().getDefaultDisplay();
      intdw = currentDisplay.getWidth();
      intdh = currentDisplay.getHeight() / 2- 100;
      try{
        BitmapFactory.Options bmpFactoryOptions = newBitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri),null, bmpFactoryOptions);
 
        bmpFactoryOptions.inSampleSize = 2;
 
        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri),null, bmpFactoryOptions);
 
        Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
            .getHeight(), bmp.getConfig());
        Canvas canvas = newCanvas(alteredBitmap);
        Paint paint = newPaint();
        canvas.drawBitmap(bmp,0,0, paint);
        Matrix matrix = newMatrix();
        matrix.setValues(newfloat[] { 1, .5f, 0,0,1,0,0,0,1});
        canvas.drawBitmap(bmp, matrix, paint);
 
        ImageView alteredImageView = (ImageView) this.findViewById(R.id.AlteredImageView);
        alteredImageView.setImageBitmap(alteredBitmap);
 
        chosenImageView.setImageBitmap(bmp);
 
      }catch(Exception e) {
        Log.v("ERROR", e.toString());
      }
    }
  }
}


//main.xml

?
1
2
3
4
5
6
7
8
<!--?xml version="1.0"encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent">
<button android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Choose Picture" android:id="@+id/ChoosePictureButton">
 
<imageview android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/ChosenImageView"></imageview>
<imageview android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/AlteredImageView"></imageview>
 
</button></linearlayout>


创建一个位图来画

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
importandroid.app.Activity;
importandroid.graphics.Bitmap;
importandroid.graphics.Canvas;
importandroid.graphics.Color;
importandroid.graphics.Paint;
importandroid.graphics.Path;
importandroid.graphics.Typeface;
importandroid.os.Bundle;
importandroid.widget.ImageView;
 
publicclass Test extendsActivity {
  ImageView drawingImageView;
  @Override
  publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
    Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
        .getDefaultDisplay().getWidth(), (int) getWindowManager()
        .getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = newCanvas(bitmap);
    drawingImageView.setImageBitmap(bitmap);
 
    Paint paint = newPaint();
    paint.setColor(Color.GREEN);
    paint.setTextSize(20);
    paint.setTypeface(Typeface.DEFAULT);
    Path p = newPath();
    p.moveTo(20,20);
    p.lineTo(100,150);
    p.lineTo(200,220);
    canvas.drawTextOnPath("this is a test", p, 0,0, paint);
  }
}



加载位图和画
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
importjava.io.IOException;
importjava.io.InputStream;
 
importandroid.app.Activity;
importandroid.content.Context;
importandroid.content.res.AssetManager;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.graphics.Canvas;
importandroid.graphics.Rect;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.View;
importandroid.view.Window;
importandroid.view.WindowManager;
 
publicclass Test extendsActivity {
  classRenderView extendsView {
    Bitmap bitmap1;
    Bitmap bitmap2;
    Rect dst = newRect();
 
    publicRenderView(Context context) {
      super(context);
      try{
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = assetManager.open("a.png");
        bitmap1 = BitmapFactory.decodeStream(inputStream);
        inputStream.close();
        Log.d("Text",""+bitmap1.getConfig());
        inputStream = assetManager.open("b.png");
        BitmapFactory.Options options = newBitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_4444;
        bitmap2 = BitmapFactory.decodeStream(inputStream, null, options);
        inputStream.close();
        Log.d("BitmapText",""+ bitmap2.getConfig());
      }catch(IOException e) {
         
      }
    }
 
    protectedvoid onDraw(Canvas canvas) {
      dst.set(50,50,350,350);
      canvas.drawBitmap(bitmap1,null, dst, null);
      canvas.drawBitmap(bitmap2,100,100,null);
      invalidate();
    }
  }
 
  @Override
  publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(newRenderView(this));
  }
}



总结一下: 
1. 从资源中获取位图 可以使用BitmapDrawable或者BitmapFactory来获取资源中的位图。 当然,首先需要获取资源: Resources res=getResources(); 使用BitmapDrawable获取位图 1. 使用BitmapDrawable (InputStream is)构造一个BitmapDrawable; 2. 使用BitmapDrawable类的getBitmap()获取得到位图; 通过Resource的函数:InputStream openRawResource(int id)获取得到资源文件的数据流后,也可以通2种方法来获取Bitmap,如下: 使用BitmapDrawable (A Drawable that wraps a bitmap and can be tiled,stretched, or aligned.) 使用BitmapDrawable (InputStream is)构造一个BitmapDrawable; 使用BitmapDrawable类的getBitmap()获取得到位图; BitmapDrawable也提供了显示位图等操作。 InputStreamis=res.openRawResource(R.drawable.pic180); // 读取资源文件获取输入流 BitmapDrawablebmpDraw=new BitmapDrawable(is); Bitmapbmp=bmpDraw.getBitmap(); 或者: BitmapDrawablebmpDraw=(BitmapDrawable)res.getDrawable(R.drawable.pic180); Bitmapbmp=bmpDraw.getBitmap(); 使用BitmapFactory (Creates Bitmap objects from various sources, includingfiles, streams, and byte-arrays.) 使用BitmapFactory类decodeStream(InputStream is)解码位图资源,获取位图。 使用BitmapFactory类Bitmap bmp=BitmapFactory.decodeResource(res,R.drawable.pic180); 方法解码位图资源。 BitmapFactory的所有函数都是static,这个辅助类可以通过资源ID、路径、文件、数据流等方式来获取位图。 以上方法在编程的时候可以自由选择,在Android SDK中说明可以支持的图片格式如下:png (preferred), jpg (acceptable), gif(discouraged),虽然bmp格式没有明确说明,但是在Android SDK Support Media Format中是明确说明了。 
2. 获取位图的信息 要获取位图信息,比如位图大小、是否包含透明度、颜色格式等,获取得到Bitmap就迎刃而解了,这些信息在Bitmap的函数中可以轻松获取到。Android SDK中对Bitmap有详细说明,阅读起来也比较容易,不在此详细说明,这里只是辅助说明以下2点: 在Bitmap中对RGB颜色格式使用Bitmap.Config定义,仅包括ALPHA_8、ARGB_4444、ARGB_8888、RGB_565,缺少了一些其他的,比如说RGB_555,在开发中可能需要注意这个小问题; Bitmap还提供了compress()接口来压缩图片,不过AndroidSAK只支持PNG、JPG格式的压缩;其他格式的需要Android开发人员自己补充了。 
3. 显示位图 显示位图可以使用核心类Canvas,通过Canvas类的drawBirmap()显示位图,或者借助于BitmapDrawable来将Bitmap绘制到Canvas。当然,也可以通过BitmapDrawable将位图显示到View中。 转换为BitmapDrawable对象显示位图 //获取位图 Bitmapbmp=BitmapFactory.decodeResource(res, R.drawable.pic180); // 转换为BitmapDrawable对象 BitmapDrawable bmpDraw=newBitmapDrawable(bmp); // 显示位图 ImageView iv2 =(ImageView)findViewById(R.id.ImageView02); iv2.setImageDrawable(bmpDraw); 使用Canvas类显示位图 这儿采用一个继承自View的子类Panel,在子类的OnDraw中显示 Java代码 public classMainActivity extends Activity { @Override public void onCreate(BundlesavedInstanceState) { super.onCreate(savedInstanceState); setContentView(new Panel(this)); } class Panel extends View{ public Panel(Context context) { super(context); } public void onDraw(Canvas canvas){ Bitmap bmp =BitmapFactory.decodeResource(getResources(), R.drawable.pic180); canvas.drawColor(Color.BLACK); canvas.drawBitmap(bmp, 10, 10,null); } } } 
4. 位图缩放 (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)借助Canvas的scale(float sx, float sy) (Preconcat the current matrix with thespecified scale.),不过要注意此时整个画布都缩放了。 (4)借助Matrix: Bitmap bmp =BitmapFactory.decodeResource(getResources(), R.drawable.pic180); Matrix matrix=new Matrix(); matrix.postScale(0.2f,0.2f); Bitmapdstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(), bmp.getHeight(),matrix,true); canvas.drawColor(Color.BLACK); canvas.drawBitmap(dstbmp,10, 10, null); 
5. 位图旋转 同样,位图的旋转也可以借助Matrix或者Canvas来实现。Matrix在线性代数中都学习过,Android SDK提供了Matrix类,可以通过各种接口来设置矩阵。结合上面的例子程序,将位图缩放例子程序在显示位图的时候前,增加位图旋转功能,修改代码如下: Matrix matrix = new Matrix(); //matrix.postScale(0.5f,0.5f); matrix.setRotate(90,120,130); canvas.drawBitmap(mbmpTest,matrix, mPaint); 除了这种方法之外,我们也可以在使用Bitmap提供的函数如下: public staticBitmap createBitmap (Bitmap source, int x, int y, int width, int height, Matrixm, boolean filter),在原有位图旋转的基础上,创建新位图。 

2014.2.5 
0 0
原创粉丝点击