Canvas drawBitmap(@NonNull Bitmap bitmap, float left, float top, @Nullable Paint paint)等比缩放+裁剪绘制

介绍

匹配最短边,然后等比例缩放,最后裁剪中间区域

先看效果图:
效果图.png
核心代码

    /**
     * 匹配适当的区域
     *
     * @param source
     * @param width
     * @param height
     * @return
     */
    private Bitmap matrixBitmap(Bitmap source, int width, int height) {
        Bitmap bitmap = null;
        if (source == null) {
            return null;
        }
        int sourceW = source.getWidth();
        int sourceH = source.getHeight();
        //等比缩放
        float sourceTmp = ((float) sourceW) / sourceH;
        int tmpHeight = 0, tmpWidth = 0;
        int dx = 0, dy = 0;
        if (width > height) {
            if (sourceW > sourceH) {
                tmpHeight = height;
                tmpWidth = (int) (tmpHeight * sourceTmp);
                dy = 0;
                dx = (tmpWidth - width) / 2;
            } else {
                tmpWidth = width;
                tmpHeight = (int) (tmpWidth / sourceTmp);
                dx = 0;
                dy = (tmpHeight - height) / 2;
            }
        } else {
            if (sourceW > sourceH) {
                tmpHeight = height;
                tmpWidth = (int) (tmpHeight * sourceTmp);
                dy = 0;
                dx = (tmpWidth - width) / 2;
            } else {
                tmpWidth = width;
                tmpHeight = (int) (tmpWidth / sourceTmp);
                dy = (tmpHeight - height) / 2;
                dx = 0;
            }
        }
        Matrix matrix = new Matrix();
        float tw = (float) tmpWidth / sourceW;
        float th = (float) tmpHeight / sourceH;
        matrix.postScale(tw, th);
        bitmap = Bitmap.createBitmap(source, 0, 0, sourceW, sourceH, matrix, false);
        //裁剪
        Bitmap cropBitmap = Bitmap.createBitmap(bitmap, dx, dy, width, height, null, false);
        bitmap.recycle();
        return cropBitmap;
    }
使用方法
 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int i = 0;
        Bitmap sourceBitmap = BitmapFactory.decodeFile(TEST_IMG);
        //mPicWidth = mPicHeight =  50dp
        Bitmap bitmap = matrixBitmap(sourceBitmap, (int) mPicWidth, (int) mPicHeight);
        sourceBitmap.recycle();

        float startX = mCurrentPos;
        Rect rect = new Rect((int) startX, 0, (int) (startX + mPicWidth), (int) mPicHeight);
        canvas.drawRect(rect, paint);
        while (i < 3) {
            Log.d(TAG, "onDraw: " + startX + " " + bitmap.getWidth());
            canvas.drawBitmap(bitmap, startX, 0, null);
            startX = startX + mPicWidth;
            i++;
        }

    }

你可能感兴趣的:(Canvas drawBitmap(@NonNull Bitmap bitmap, float left, float top, @Nullable Paint paint)等比缩放+裁剪绘制)