简体   繁体   English

在自定义ImageView中缩放图像

[英]Scale image within custom ImageView

I'm extending ImageView in order to manually scale an image within the view. 我正在扩展ImageView以便在视图中手动缩放图像。 I want to scale an image to fill the width of the custom view, and then draw it to the canvas, however, I'm unable to get the view width using this.getWidth() It just returns 0, as the view has not yet been drawn and so has dimensions 0 by 0. 我想缩放图像以填充自定义视图的宽度,然后将其绘制到画布上,但是,我无法使用this.getWidth()获得视图宽度。它只返回0,因为视图没有尚未绘制,因此尺寸为0 x 0。

Currently I have the following in my main.xml: 目前,我的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"
    />

The custom class is as follows: 自定义类如下:

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);
    }

}

My Main.java class is: 我的Main.java类是:

public class Main extends Activity {

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

I can't use 我不能用
Bitmap.createScaledBitmap(background, view.getWidth(), view.getHeight(), false)
as the view hasn't yet been drawn, how would I go about scaling the image to fill the view/screen width at this point? 由于尚未绘制视图,我现在将如何缩放图像以填充视图/屏幕宽度?

Thanks in advance. 提前致谢。

I believe what you want to do could also be achieved by using ImageView directly in conjunction with the scaleType attribute. 我相信您也可以通过将ImageView与scaleType属性直接结合使用来实现。 Either use fitXY or centerCrop , depending on your needs. 根据需要使用fitXYcenterCrop

But to answer the question, you can only use getWidth() and getHeight() after layout() has been called. 但是要回答这个问题,只能在调用layout()之后使用getWidth()和getHeight()。 So you should be able to use the values inside your onDraw method. 因此,您应该能够使用onDraw方法中的值。

Also you could use another drawBitmap method so you wouldn't have to create a new bitmap in memory. 另外,您可以使用另一个drawBitmap方法,这样就不必在内存中创建新的位图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM