2013-04-30 63 views
0

我想绘制一个简单的.png文件到屏幕。我正在使用以下代码:Android应用程序 - 从活动绘制位图

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

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

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