主要原理:
- 创建画布
- 创建指定位置的矩形
- 根据所选矩形的中心点旋转
- 裁剪掉bitmap的空白处(此处借鉴了这个网站的代码,感谢)
代码部分:
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.Log;
import java.util.Arrays;
public class BitmapUtil {
public static final String TAG = "BitmapUtil";
public static Bitmap clipBitMap(Bitmap bitmap, float x, float y, float width, float height, float rot) {
float left = x;
float top = y;
float right = x + width;
float bottom = y + height;
if (bitmap == null) {
Log.e(TAG, "输入的bitmap是空的!");
return Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
}
Bitmap bitmap1 = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas targetCanvas = new Canvas(bitmap1);
Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
RectF rect = new RectF(left, top, right, bottom);
targetCanvas.drawRect(rect, new Paint(Paint.ANTI_ALIAS_FLAG));
targetCanvas.rotate(-rot, (left + right) / 2, (top + bottom) / 2);
targetCanvas.drawBitmap(bitmap, 0, 0, bitmapPaint);
Bitmap bitmap2 = crop(bitmap1);
return bitmap2;
}
public static Bitmap crop(Bitmap bitmap) {
int height = bitmap.getHeight();
int width = bitmap.getWidth();
int[] empty = new int[width];
int[] buffer = new int[width];
Arrays.fill(empty, 0);
int top = 0;
int left = 0;
int bottom = height;
int right = width;
for (int y = 0; y < height; y++) {
bitmap.getPixels(buffer, 0, width, 0, y, width, 1);
if (!Arrays.equals(empty, buffer)) {
top = y;
break;
}
}
for (int y = height - 1; y > top; y--) {
bitmap.getPixels(buffer, 0, width, 0, y, width, 1);
if (!Arrays.equals(empty, buffer)) {
bottom = y;
break;
}
}
empty = new int[height];
buffer = new int[height];
Arrays.fill(empty, 0);
for (int x = 0; x < width; x++) {
bitmap.getPixels(buffer, 0, 1, x, 0, 1, height);
if (!Arrays.equals(empty, buffer)) {
left = x;
break;
}
}
for (int x = width - 1; x > left; x--) {
bitmap.getPixels(buffer, 0, 1, x, 0, 1, height);
if (!Arrays.equals(empty, buffer)) {
right = x;
break;
}
}
return Bitmap.createBitmap(bitmap, left, top, right - left + 1, bottom - top + 1);
}
}