Android应用程序 - 从活动中绘制位图

时间:2013-04-30 19:40:17

标签: java android bitmap

我正在尝试将简单的.png文件绘制到屏幕上。我使用以下代码:

public class EditMindMapActivity extends Activity {

    private Button HomeButton;
    private Button SaveButton;

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

        //creating dummy array:
        List<String> mindMapArrayListLabels = new ArrayList<String>();
        int mindMapArrayListImgs[] = new int[100]; //length 100 is arbitrary

        mindMapArrayListLabels.add("Schedule");
        mindMapArrayListImgs[0] = R.drawable.pyr01;
        mindMapArrayListLabels.add("Stuff01");
        mindMapArrayListImgs[1] = R.drawable.tube01;
        mindMapArrayListLabels.add("Stuff02");
        mindMapArrayListImgs[2] = R.drawable.cone01;

        //draw the first image to screen
        View view01 = new View(this); 
        //find relative layout, attach view to it.
        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.RelativeLayout01);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
        relativeLayout.addView(view01,lp);
        Canvas canvas01 = new Canvas();
        canvas01.drawBitmap(BitmapFactory.decodeResource(getResources(), mindMapArrayListImgs[0]), 10, 10, null);
        view01.draw(canvas01);
    }
}

以上内容无效 - 屏幕显示为空白。我想在屏幕上显示图像R.drawable.pyr01。

1 个答案:

答案 0 :(得分:1)

创建自定义视图并绘制图像。将自定义视图作为子项添加到相对布局中。根据您的需要修改以下内容。

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/rl"
tools:context=".MainActivity" >

    <Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:text="Button" />

   </RelativeLayout>

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rl);
    MyView mv = new MyView(this);
    relativeLayout.addView(mv);
}

class MyView extends View
{

    public MyView(Context context) {
        super(context);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.afor), 100 ,100, null);
    }

}

产生快照

enter image description here