3.2 在位图上绘制位图

    在深入探讨用来更改图像的具体机制之前,让我们看看如何创建一个新的空位图对象,并在其上绘制已有的位图。这是将用来创建图像的更改版本的过程。  

    上述示例获得了一个位图对象,使用用户选择的一幅图像对其进行实例化。正如子啊第一章中所介绍的那样,通过BitmapFactory的decodeStream方法进行实例化。

1 Bitmap bmp=BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri),null,bmpBitmapFactoryOptions);

   为了使用该位图对象作为图像编辑实验的数据源,需要能够以所应用的效果在屏幕上绘制该位图。此外,最好能够将它绘制到可以用来保存结果的对象中。因此,需要创建一个空的位图对象,其尺寸与现有位图对象的尺寸相同,并且将它作为更改位图对象的目标。

1 Bitmap alteredBitmap=Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());

  当创建这个更改位图对象alteredBitmap时,其宽度、高度和Bitmap.Config对象作为参数,因此将获得一个可变的位图对象作为返回值。可变意味着可以更改该位图表示的像素值。如果有一个不可变的位图对象,那么不能对其进行绘制。此方法调用时唯一可以实例化一个可变位图对象的方式之一。

  下面需要的是一个Canvas(画布)对象。正如你所希望的那样,在Android中画布是可以再其上绘制的对象。可以通过其在其构造函数中传入一个位图对象来创建Canvas对象,随后就可以将其用于绘制。

1 Canvas canvas=new Canvas(alteredBitmap);

   最后,将需要一个Paint(画刷)对象。当进行实际的绘制时,Paint对象将发挥作用。具体而言,它使得我们能够改变诸如颜色和对比度之类的参数,后面章节将对其详细的介绍。目前采用默认的Paint对象。

1 Paint paint=new Paint();

   现在,为了在一个空的可变位图对象上绘制原位图对象,我们已经具备了而所有必须的组件。下面将刚才描述的所有代码汇总在一起。

1                 Bitmap bmp=BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri),null,bmpBitmapFactoryOptions);
2                 Bitmap alteredBitmap=Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
3                 Canvas canvas=new Canvas(alteredBitmap);
4                 Paint paint=new Paint();
5                 canvas.drawBitmap(bmp, 0, 0, paint);
6                 ImageView alteredImageView=(ImageView) ChoosePicture.this.findViewById(R.id.AlteredImageView);
7                 alteredImageView.setImageBitmap(alteredBitmap);

   正在使用的Canvas对象上的drawBitmap方法接受源位图对象x和y偏移及Paint对象作为参数。这使得alteredBitmap对象将包含与初始位图完全相同的信息。

   可以将所有这些代码插入到“选择图片”示例中。它应该接近onActivityResult方法的末尾处,在bmp=BitmapFactory.decodeStream行之后。小心不要重复该行,如上述代码所示;也不要忘了添加适当的import语句。

   之后,我们想要显示alteredBitmap对象。为此,使用标准的ImageView,并以alteredBitmap作为参数调用setImageBitmap。这会假设我们有一个ImageView,并且已经在布局XML中声明其id为AlteredImageView

   以下是更新后的布局XML,它用于完整的“选择图片”示例,其中包含了初始的ImageView以及用于alteredBitmap的新的ImageView。

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     android:layout_width="match_parent"
 3     android:layout_height="match_parent"
 4     android:orientation="vertical"
 5     >
 6     <Button 
 7         android:layout_width="fill_parent"
 8         android:layout_height="wrap_content"
 9         android:text="Choose Picture"
10         android:id="@+id/ChoosePictureButton" />
11     <ImageView 
12           android:layout_width="wrap_content"
13           android:layout_height="wrap_content"
14           android:id="@+id/chosenImageView"
15         />
16     <ImageView 
17           android:layout_width="wrap_content"
18           android:layout_height="wrap_content"
19           android:id="@+id/AlteredImageView"
20         />
21 </LinearLayout>

 

posted on 2014-08-23 09:05  宁静致远,一览众山小  阅读(361)  评论(0编辑  收藏  举报

导航