// 获取位图
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic180);
// 转换为BitmapDrawable对象
BitmapDrawable bmpDraw=new BitmapDrawable(bmp);
// 显示位图
ImageView iv2 = (ImageView)findViewById(R.id.ImageView02);
iv2.setImageDrawable(bmpDraw); 复制代码使用Canvas类显示位图
这儿采用一个继承自View的子类Panel,在子类的OnDraw中显示
Java代码
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
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 the specified scale.),不过要注意此时整个画布都缩放了。
(4)借助Matrix:
Java代码
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);
Matrix matrix=new Matrix();
matrix.postScale(0.2f, 0.2f);
Bitmap dstbmp=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 static Bitmap createBitmap (Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter),在原有位图旋转的基础上,创建新位图。
总结说明
对位图的操作,结合Android SDK中的类,详细的介绍完了。最后还需要强调的是:这篇文章只是对Android SDK中代码阅读分析,它代替不了你阅读Android SDK,深入的学习还是要仔细的阅读Android SDK。
转载自: