本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处!
写完上一篇后,总觉得介绍的知识点不多,只是一种在UI线程解析加载图片,两种在子线程解析,在UI线程加载图片,就这个区别。
关于图片和ImageView,其实有更多可以介绍的,比如在解析图片前获得图片的宽高,用来做图片适配;比如等比例缩小图片,以减小内存占用;比如图片旋转效果等等。
第一个问题和第二个问题:
BitmapFactory.Options options = new BitmapFactory.Options();
/*
* If set to true, the decoder will return null (no bitmap), but the
* out... fields will still be set, allowing the caller to query the
* bitmap without having to allocate the memory for its pixels.
*/
options.inJustDecodeBounds = true;
String url=Environment.getExternalStorageDirectory().getPath() +"/test.jpg";//sdcard/test.jpg
BitmapFactory.decodeFile(url,options);
int outWidth=options.outWidth;//获得图片的宽
int outHeight=options.outHeight;//获得图片的高
int width=100;//放图片组件的宽
int height=100;//放图片组件的高
double shink=outHeight*outWidth/width/height;//缩小的比例
options.inSampleSize=(int) Math.sqrt(shink);//inSampleSize设置,则缩小比例即它的平方,如2则比例为1/4。Bitmap bitmap=BitmapFactory.decodeFile(url, options);//此值就是我们所需要的值
以下是官方提供的方法:public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
第三个问题:Matrix来翻转、剪切图片之后再讲。matrix通过设置postRotate来进行翻转,无论45度还是90度Matrix matrix = new Matrix();
matrix.postRotate(45);int x=0;//The x coordinate of the first pixel in sourceint y=0;// The y coordinate of the first pixel in sourceint width=bitmap.getWidth();//The number of pixels in each rowint height=bitmap.getHeight();// The number of rows
Bitmap finalBitmap = Bitmap.createBitmap(bitmap, x, y, width ,height, matrix, true);
mImg.setImageBitmap(finalBitmap);
剪切主要改变x,y,width和height,来获得相应尺寸和图形的Bitmapmatrix.postRotate的结果如下图
matrix.postScale(1,-1);倒立的结果如下图
第四个问题:Bitmap.Config几种类型间的区别
A:alpha R:red G:green B:blue
ARGB_8888 32位,8byte每个像素 透明度为8
ARGB_4444 16位,4byte每个像素 透明度为4
ALPHA_8 8位,1byte每个像素 透明度为8 没有颜色
RGB_565 16位,2byte每个像素 无透明度
第五个问题:canvas画图
clipRect:要求画制的区域,有left、right、top、bottom4个参数(相对父布局而言,scrollTo同理)
drawArc:画弧线
drawRect:画长方形