当前位置: 代码迷 >> Android >> 一行学android之对资源图片进行比例缩放 (27)
  详细解决方案

一行学android之对资源图片进行比例缩放 (27)

热度:52   发布时间:2016-04-28 02:01:24.0
一起学android之对资源图片进行比例缩放 (27)

效果图:



在平时加载图片时,我会使用SetImageBitmap、setImageResource、BitmapFactory.decodeResource来设置一张图


片通过以上方法来设置图片时,会通过Java层的createBitmap来完成,这样的话会消耗很多内存,容易导致


OOM(Out Of Memory),因此推荐使用BitmapFactory.Options这个类来设置一张资源图。


参看以下代码:

public class MainActivity extends Activity {	private ImageView imageView1;	private ImageView imageView2;	Bitmap mBitmap;	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.image);		initView();		}	private void initView(){		imageView1=(ImageView)findViewById(R.id.imageView1);		imageView2=(ImageView)findViewById(R.id.imageView2);		//读取资源图片		mBitmap=readBitMap();		//对资源图片进行缩放		imageView2.setImageBitmap(zoomBitmap(mBitmap, mBitmap.getWidth()/4, mBitmap.getHeight()/4));	}			/**	 * 读取资源图片	 * @return 	 */	private Bitmap readBitMap(){		BitmapFactory.Options opt=new BitmapFactory.Options();		/*		 * 设置让解码器以最佳方式解码		 */		opt.inPreferredConfig=Bitmap.Config.RGB_565;		//下面两个字段需要组合使用		opt.inPurgeable=true;		opt.inInputShareable=true;		/*		 * 获取资源图片		 */		InputStream is=this.getResources().openRawResource(R.drawable.mei);		return BitmapFactory.decodeStream(is, null, opt);	}		/**	 * 缩放图片	 * @param bitmap	 * @param w	 * @param h	 * @return	 */	public  Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {		int width = bitmap.getWidth();		int height = bitmap.getHeight();		Matrix matrix = new Matrix();		float scaleWidht = ((float) w / width);		float scaleHeight = ((float) h / height);		/*		 * 通过Matrix类的postScale方法进行缩放		 */		matrix.postScale(scaleWidht, scaleHeight);		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);		return newbmp;	}	}

image.xml:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <ImageView        android:id="@+id/imageView1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:src="@drawable/mei" />    <ImageView        android:id="@+id/imageView2"        android:layout_width="wrap_content"        android:layout_below="@+id/imageView1"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        android:src="@drawable/mei" /></RelativeLayout>



转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/44281087 情绪控_





  相关解决方案