【问题标题】:Android: How can I centerCrop the background of a view?Android:如何居中裁剪视图的背景?
【发布时间】:2023-03-05 03:51:02
【问题描述】:

我不想在视图中插入图像视图,我只想将位图设置为视图的背景。但我想要位图 centerCropped。默认情况下,位图背景会被拉伸以适应视图的边界。

【问题讨论】:

    标签: android


    【解决方案1】:

    您可以通过实现自定义背景可绘制对象来做到这一点。

    我实现了一个BitmapDrawable 的子类,它可以居中裁剪位图(基本上覆盖了onDraw(Canvas) 方法)。

    代码:

    package com.github.premnirmal;
    
    import android.content.res.Resources;
    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Matrix;
    import android.graphics.drawable.BitmapDrawable;
    
    /**
     * A subclass of bitmap drawable that scales the bitmap to CenterCrop
     * Copyright Prem Nirmal 2016 MIT License
     * @author PremNirmal
     */
    public class CenterCropBitmapDrawable extends BitmapDrawable {
    
      private final int viewWidth, viewHeight;
    
      public CenterCropBitmapDrawable(Resources res, Bitmap bitmap, int viewWidth, int viewHeight) {
        super(res, bitmap);
        this.viewWidth = viewWidth;
        this.viewHeight = viewHeight;
      }
    
      @Override public void draw(Canvas canvas) {
        final Matrix drawMatrix = new Matrix();
        final int dwidth = getIntrinsicWidth();
        final int dheight = getIntrinsicHeight();
    
        final int vwidth = viewWidth;
        final int vheight = viewHeight;
    
        float scale;
        float dx = 0, dy = 0;
        int saveCount = canvas.getSaveCount();
        canvas.save();
        if (dwidth * vheight > vwidth * dheight) {
          scale = (float) vheight / (float) dheight;
          dx = (vwidth - dwidth * scale) * 0.5f;
        } else {
          scale = (float) vwidth / (float) dwidth;
          dy = (vheight - dheight * scale) * 0.5f;
        }
    
        drawMatrix.setScale(scale, scale);
        drawMatrix.postTranslate(Math.round(dx), Math.round(dy));
        canvas.concat(drawMatrix);
    
        canvas.drawBitmap(getBitmap(), 0, 0, getPaint());
    
        canvas.restoreToCount(saveCount);
      }
    }
    

    【讨论】:

    • 您可以添加此代码而不是放置链接吗?这样未来的读者仍然会看到代码(以防要点被删除)。
    猜你喜欢
    • 2021-07-05
    • 2015-10-22
    • 2016-01-19
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多