赞
踩
Bitmap
和 Drawable
是 Android 图形绘制的两种常用方式,它们有各自的特点和使用场景。下面将详细解释它们之间的区别,并通过示例代码说明如何使用它们。
// 从资源文件加载Bitmap
Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.example_image);
// 获取Bitmap的宽高
intwidth= bitmap.getWidth();
intheight= bitmap.getHeight();
// 在ImageView中显示Bitmap
ImageView imageView= findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
// 从资源文件加载Drawable
Drawable drawable= getResources().getDrawable(R.drawable.example_image, null);
// 在ImageView中显示Drawable
ImageView imageView= findViewById(R.id.imageView);
imageView.setImageDrawable(drawable);
recycle()
方法)。以下示例展示了如何在运行时切换ImageView的Drawable:
ImageViewimageView= findViewById(R.id.imageView);
// 切换到BitmapDrawableBitmapbitmap= BitmapFactory.decodeResource(getResources(), R.drawable.example_image);
DrawablebitmapDrawable=newBitmapDrawable(getResources(), bitmap);
imageView.setImageDrawable(bitmapDrawable);
// 切换到VectorDrawableDrawablevectorDrawable= getResources().getDrawable(R.drawable.example_vector, null);
imageView.setImageDrawable(vectorDrawable);
// 切换到ShapeDrawableShapeDrawableshapeDrawable=newShapeDrawable(newOvalShape());
shapeDrawable.getPaint().setColor(Color.RED);
imageView.setImageDrawable(shapeDrawable);
Bitmap
时,更适合图像处理和操作,可以直接访问像素数据,但需要小心内存管理。Drawable
时,更适合通用的图形绘制,提供更丰富的功能和子类,适用于更复杂的图形操作和动画。根据具体的需求选择使用 Bitmap
或 Drawable
,可以帮助更好地实现图形绘制和图像处理任务。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。