获取屏幕分辨率:
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
screenWidth = mDisplayMetrics.widthPixels;
screenHeight = mDisplayMetrics.heightPixels;
从网络获取图片:
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Looper.prepare();
URL myUrl = null;
Bitmap bitmap;
String imageId = null;
try {
imageId = (String) dataFirst.get(i).get("item_image");
imageId = imageId.substring(1,imageId.length()-1);
myUrl = new URL(imageId);
HttpURLConnection conn = (HttpURLConnection)myUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
//原始大小
primaryWidth = bitmap.getWidth();
primaryHeight = bitmap.getHeight();
//初始比例为1
scaleWidth = scaleHeight = 1;
if(screenWidth == 720 && screenHeight == 1280){
bitmap = scale(1, 1,bitmap);
}else{
bitmap = scale(1.8, 1.8,bitmap);
}
bitmapList.add(bitmap);
is.close();
new Handler(getActivity().getMainLooper()).post(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
imagess();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
根据分辨率缩放图片:
/**
* 缩放
*/
private Bitmap scale(double scale_width, double scale_height,Bitmap bmp) {
//这种方法,有点不好是:如果图片大小超出屏幕会报错。
// if((scale_width > 1 && scaleWidth * primaryWidth >= getWindowManager().getDefaultDisplay().getWidth())
// || (scale_width > 1 && scale_height * primaryHeight >= getWindowManager().getDefaultDisplay().getHeight())){
// bt_bigger.setEnabled(false);
// }else {
// bt_bigger.setEnabled(true);
// }
scaleWidth = scaleWidth * scale_width; //缩放到原来的*倍
scaleHeight = scaleHeight * scale_height;
Matrix matrix = new Matrix(); //矩阵,用于图片比例缩放
matrix.postScale((float)scaleWidth, (float)scaleHeight); //设置高宽比例(三维矩阵)
//缩放后的BitMap
Bitmap newBmp = Bitmap.createBitmap(bmp, 0, 0, primaryWidth, primaryHeight, matrix, true);
//重新设置BitMap
return newBmp;
}