import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Bitmap.Config;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
public class MyBitmapFactory {
/**
* 根据限制参数输出图片,图片不会拉伸
*
* @param bitmap 原始bitmap
* @param maxWidth 输出容器的最大宽度,-1为不限制
* @param maxHeight 输出容器的最大高度,-1为不限制
* @param scale_w_h 输出图片的宽高比例,-1为按图比例
* @param rotate 原始bitmap需要旋转的角度 0,90,180,270...
* @param config 像素类型
*/
public static Bitmap CreateBitmap(Bitmap bitmap, int maxWidth, int maxHeight, float scale_w_h, int rotate, Config config)
{
Bitmap outBmp = null;
if(bitmap != null)
{
int inW = bitmap.getWidth();
int inH = bitmap.getHeight();
if(rotate % 180 != 0)
{
inW += inH;
inH = inW - inH;
inW -= inH;
}
MyRect clipRect;
if(scale_w_h > 0)
{
clipRect = MakeRect(inW, inH, scale_w_h);
}
else
{
clipRect = new MyRect();
clipRect.left = 0;
clipRect.top = 0;
clipRect.width = inW;
clipRect.height = inH;
}
float scale = 1;
if(maxWidth > 0 && maxHeight > 0 && (maxWidth < clipRect.width || maxHeight < clipRect.height))
{
float scale1 = (float)maxWidth / clipRect.width;
float scale2 = (float)maxHeight / clipRect.height;
if(scale1 <= scale2)
{
scale = scale1;
}
else
{
scale = scale2;
}
}
else if(maxWidth > 0)
{
if(maxWidth < clipRect.width)
{
scale = (float)maxWidth / clipRect.width;
}
}
else if(maxHeight > 0)
{
if(maxHeight < clipRect.height)
{
scale = (float)maxHeight / clipRect.height;
}
}
float bmpW = clipRect.width * scale;
if(bmpW < 1)
{
bmpW = 1;
}
float bmpH = clipRect.height * scale;
if(bmpH < 1)
{
bmpH = 1;
}
float centerX = bmpW / 2f;
float centerY = bmpH / 2f;
Matrix matrix = new Matrix();
matrix.postTranslate((bmpW - bitmap.getWidth()) / 2f, (bmpH - bitmap.getHeight()) / 2f);
matrix.postRotate(rotate, centerX, centerY);
matrix.postScale(scale, scale, centerX, centerY);
outBmp = Bitmap.createBitmap((int)bmpW, (int)bmpH, config);
Canvas canvas = new Canvas(outBmp);
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
Paint pt = new Paint();
pt.setAntiAlias(true);
pt.setFilterBitmap(true);
canvas.drawBitmap(bitmap, matrix, pt);
}
return outBmp;
}
/**
* 返回符合比例的图片裁剪矩形
*
* @param width 图片的宽
* @param height 图片的高
* @param scale_w_h 宽高比例
*/
public static MyRect MakeRect(float width, float height, float scale_w_h)
{
MyRect outRect = new MyBitmapFactory.MyRect();
outRect.width = width;
outRect.height = width / scale_w_h;
if(outRect.height > height)
{
outRect.height = height;
outRect.width = height * scale_w_h;
}
outRect.left = (width - outRect.width) / 2f;
outRect.top = (height - outRect.height) / 2f;
return outRect;
}
static class MyRect{
float width;
float height;
float left;
float top;
}