How to insert an image with canvas?

2019-09-04 09:24发布

问题:

I´m trying to insert a simple image with canvas in Android with the next code, but when i try to execute in the smartphone, only appears a white screen without image.

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
    }

}

class Lienzo extends View {
    private Drawable theimage;

    public Lienzo(Context context) {
        super(context);
        Resources res = context.getResources();
        theimage = res.getDrawable(R.drawable.ic_launcher);
        theimage.setBounds(30, 30, 200, 200);
    }

    protected void onDraw(Canvas canvas) {
        theimage.draw(canvas);
    }
}

I´m sure this is a foolishness but, what´s wrong in the code? The idea is simple, insert an image in the canvas.

回答1:

I found the answer: I add a view (Lienzo) to the layout. Answer found in this spanish web.

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.layout1);
    Lienzo image = new Lienzo(this);
    layout1.addView(image);     
}

Thanks Xavier Falempin, you inspired me.