Android獲取兩張圖片重疊部分,並融合
阿新 • • 發佈:2019-02-17
/**
* 融合圖裁剪
* @param big 底圖
* @param small 小圖
* @param xInRatio 小圖在底圖中的橫座標(相對於底圖寬的比例)
* @param yInRatio 小圖在底圖中的縱座標(相對於底圖高的比例)
* @param alpha 小圖的透明度 0~255
* @return
*/
public static Bitmap mergeWithCrop(Bitmap big,Bitmap small,float xInRatio,float yInRatio,int alpha){
int smallW = small.getWidth();
int smallH = small.getHeight();
int bigW = big.getWidth();
int bigH = big.getHeight();
int smallX = (int)(bigW*xInRatio);
int smallY = (int)(bigH*yInRatio);
int bigX = 0;
int bigY = 0;
Rect sRect = new Rect(smallX, smallY, smallX+smallW, smallY+smallH);
Rect bRect = new Rect(bigX, bigY, bigX+bigW, bigY+bigH);
Rect overlap = intersect(sRect, bRect);
int overlayW = overlap.right - overlap.left;
int overlayH = overlap.bottom - overlap.top;
//防止紅外圖完全覆蓋可見光圖時報錯。
if (overlap.left == 0 && overlap.top == 0){
overlayW--;
overlayH--;
}
Bitmap newBmp = Bitmap.createBitmap(big,overlap.left,overlap.top,overlayW,overlayH);
big.recycle();
Canvas canvas = new Canvas(newBmp);
Paint paint = new Paint();
paint.setAlpha(alpha);
canvas.drawBitmap(small, smallX >= 0 ? 0 : smallX, smallY >= 0 ? 0 : smallY, paint);
small.recycle();
return newBmp;
}
/**
* 求矩形的重疊區域
* @param r1
* @param r2
* @return
*/
public static Rect intersect(Rect r1,Rect r2){
Rect r = new Rect();
r.left = Math.max(r1.left, r2.left);
r.top = Math.max(r1.top, r2.top);
r.right = Math.min(r1.right, r2.right);
r.bottom = Math.min(r1.bottom, r2.bottom);
if (r.left > r.right || r.top > r.bottom)
r = null;
return r;
}