How to insert an image with canvas?

那年仲夏 提交于 2019-12-12 02:00:01

问题


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.



来源:https://stackoverflow.com/questions/27250143/how-to-insert-an-image-with-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!