/* *
* 根据缩略的宽高比例和设定的最大宽高设置图片的宽高 长图会截取中间一段
*/
public
static
synchronized
Bitmap readBitmap(String key,
int
width,
int
height) {
File bitmapFile =
null
;
Bitmap bitmap =
null
;
boolean
toLongOrWidth =
false
;
boolean
widthbigger =
false
;
try
{
bitmapFile = getFile(key);
}
catch
(FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if
(bitmapFile !=
null
) {
BitmapFactory.Options options =
new
Options();
options.inJustDecodeBounds =
true
;
try
{
BitmapFactory.decodeStream(
new
FileInputStream(bitmapFile),
null
, options);
int
outheight = options.outHeight;
int
outwidth = options.outWidth;
float
rate;
if
(outheight > outwidth) {
rate = (
float
) outheight / (
float
) outwidth;
if
(rate >
2.0
) {
toLongOrWidth =
true
;
}
height = (
int
) (width * rate);
widthbigger =
false
;
}
else
{
rate = (
float
) outwidth / (
float
) outheight;
if
(rate >
2.0
) {
toLongOrWidth =
true
;
}
width = (
int
) (height * rate);
widthbigger =
true
;
}
int
size = calculateInSampleSize(options, width, height);
options.inSampleSize = size;
options.inJustDecodeBounds =
false
;
bitmap = BitmapFactory.decodeStream(
new
FileInputStream(
bitmapFile),
null
, options);
Bitmap dst = Bitmap.createScaledBitmap(bitmap, width, height,
false
);
if
(toLongOrWidth) {
if
(widthbigger) {
int
oldwidth = width;
width = (
int
) ((
float
) height * (
float
)
1.77
);
dst = Bitmap.createBitmap(dst, (oldwidth - width) /
2
,
0
, width, height);
}
else
{
int
oldheight = height;
height = (
int
) ((
float
) width * (
float
)
1.77
);
dst = Bitmap.createBitmap(dst,
0
,
(oldheight - height) /
2
, width, height);
}
Bitmap newb = Bitmap.createBitmap(dst.getWidth(),
dst.getHeight(), Config.ARGB_8888);
Canvas canvasTmp =
new
Canvas(newb);
canvasTmp.drawColor(Color.TRANSPARENT);
Paint p =
new
Paint();
Typeface font = Typeface.create(
"宋体"
, Typeface.BOLD);
p.setAntiAlias(
true
);
// 设置画笔为无锯齿
p.setColor(Color.WHITE);
p.setTypeface(font);
p.setTextSize(ImageUtils.dp2px(HoHoApplication.mAppContext,
(
float
)
12
));
canvasTmp.drawBitmap(dst,
0
,
0
, p);
Paint p2 =
new
Paint();
p2.setColor(Color.parseColor(
"#77000000"
));
Rect r =
new
Rect(
0
, dst.getHeight()
- ImageUtils.dp2px(HoHoApplication.mAppContext,
(
float
)
24
), dst.getWidth(),
dst.getHeight());
canvasTmp.drawRect(r, p2);
canvasTmp.drawText(
"长图"
,
dst.getWidth()
/
2
- ImageUtils.dp2px(
HoHoApplication.mAppContext,
(
float
)
12
),
dst.getHeight()
- ImageUtils.dp2px(
HoHoApplication.mAppContext,
(
float
)
6
), p);
canvasTmp.save(Canvas.ALL_SAVE_FLAG);
canvasTmp.restore();
dst = newb;
}
if
(bitmap != dst) {
// 如果没有缩放,那么不回收
bitmap.recycle();
// 释放Bitmap的native像素数组
}
return
dst;
}
catch
(FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return
bitmap;
}