学习笔记,如何将矩形图片不失真地转换为正方形,附上代码及图示
左图: left=( nHeight - nWidth )/2
右图: top=(nWidth - nHeight)/2
//获取原始宽高,并获取宽高中较大的
int nWidth = bitmap_org.getWidth();
int nHeight = bitmap_org.getHeight();
int nMax = Math.max(nWidth,nHeight);
//新建一个正方形的bitmap
Bitmap bitmap = Bitmap.createBitmap( nMax, nMax, bitmap_org.getConfig());
float left = 0;
float top = 0;
if ( nWidth >= nHeight)
{
int nLen= nWidth - nHeight ;
top = (float) (nLen / 2.0) ;
}
else
{
int nLen= nHeight - nWidth ;
left = (float) (nLen / 2.0) ;
}
Canvas canvas = new Canvas( bitmap );
//生成正方形
canvas.drawBitmap( bitmap_org, left , top, null );
canvas = null;