【问题标题】:Scale image within custom ImageView在自定义 ImageView 中缩放图像
【发布时间】:2011-08-21 20:45:17
【问题描述】:

我正在扩展 ImageView 以便在视图中手动缩放图像。我想缩放图像以填充自定义视图的宽度,然后将其绘制到画布上,但是,我无法使用 this.getWidth() 获取视图宽度 它只返回 0,因为视图尚未绘制,因此尺寸为 0 x 0。

目前我的 main.xml 中有以下内容:

<com.android.myapp.BackgroundView
    android:id="@+id/background_view"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:src="@drawable/background"
    android:dither="true"
    />

自定义类如下:

public class BackgroundView extends ImageView {

    private Paint paint;
    private Bitmap background;

    public BackgroundView(Context context) {
        super(context);
        paint = new Paint();
        loadBitmap();
    }

    public BackgroundView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        loadBitmap();
    }

    public void loadBitmap() {
        BitmapDrawable src = (BitmapDrawable) this.getDrawable();
        background = src.getBitmap();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(background, 0, 0, paint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}

我的 Main.java 类是:

public class Main extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

我不能使用
Bitmap.createScaledBitmap(background, view.getWidth(), view.getHeight(), false)
由于尚未绘制视图,此时我将如何缩放图像以填充视图/屏幕宽度?

提前致谢。

【问题讨论】:

    标签: android view canvas bitmap imageview


    【解决方案1】:

    我相信你想要做的也可以通过直接使用 ImageView 和scaleType 属性来实现。根据您的需要,使用 fitXYcenterCrop

    但要回答这个问题,您只能在调用 layout() 之后使用 getWidth() 和 getHeight()。因此,您应该能够在 onDraw 方法中使用这些值。

    您也可以使用另一个drawBitmap 方法,这样您就不必在内存中创建新的位图。

    【讨论】:

      猜你喜欢
      • 2020-06-18
      • 2018-07-19
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多