CutUtil.java
2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.hjx.parent.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
import android.view.ViewTreeObserver;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.hjx.parent.function.Function1;
public class CutUtil {
public static float[] measureBitmap(View view, Bitmap bitmap) {
float realW;
float realH;
float offsetX;
float offsetY;
float vp = 1f * view.getWidth() / view.getHeight();
float bp = 1f * bitmap.getWidth() / bitmap.getHeight();
if (vp > bp) {
realW = view.getHeight() * bp;
realH = (float) view.getHeight();
offsetY = 0f;
offsetX = (view.getWidth() - realW) * 0.5f;
} else if (vp < bp) {
realW = (float) view.getWidth();
realH = view.getWidth() * (1f / bp);
offsetX = 0f;
offsetY = (view.getHeight() - realH) * 0.5f;
} else {
realW = (float) view.getWidth();
realH = (float) view.getHeight();
offsetX = 0f;
offsetY = 0f;
}
return new float[]{realW, realH, offsetX, offsetY};
}
public static Bitmap cut(Bitmap source, float x, float y, int w, int h, Context context) {
// 获取 Glide 的 BitmapPool
BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
// 从 BitmapPool 中获取可复用的 Bitmap
Bitmap result = bitmapPool.get(w, h, source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888);
// 填充白色背景
result.eraseColor(Color.WHITE);
// 创建画布并绘制
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
canvas.drawBitmap(source, -x, -y, paint);
return result;
}
public static void onLayoutReady(final View view, final Function1<View> action) {
view.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
action.invoke(view);
}
}
);
}
}