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.util.Base64; 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; import java.io.ByteArrayOutputStream; 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 action) { view.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { view.getViewTreeObserver().removeOnGlobalLayoutListener(this); action.invoke(view); } } ); } public static byte[] bitmapToByteArray(Bitmap bitmap) { ByteArrayOutputStream output = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output); return output.toByteArray(); } public static String bitmapToBase64(Bitmap bitmap, Boolean usePrefix) { String base64 = Base64.encodeToString(bitmapToByteArray(bitmap), Base64.NO_WRAP); if (usePrefix) return "data:image/jpeg;base64," + base64; else return base64; } }