2016-01-17 26 views
0

我想绘制ImageView,当我尝试创建位图时,程序崩溃。 首先我创建可变在ImageView上绘图 - createBitmap崩溃

private ImageView backgroudn; 

在onCreate方法我指出背景在我的xml文件对象。

this.backgroudn = (ImageView) findViewById(R.id.ivbackground); 
drawGrid(); 

可是现在,我要画这个的ImageView的功能drawGrid(),它首先返回我的ImageView为大小宽度= 0和高度= 0。为什么我做了什么错?

private void drawGrid() { 

    int height = this.backgroudn.getHeight(); 
    int width = this.backgroudn.getWidth(); 

    // return's height = width = 0 
    System.out.println("height: " + height + " width: " + width); 

    // where program crashes. 
    Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 


    Canvas c = new Canvas(bm); 
    Paint p = new Paint(); 
    p.setColor(Color.BLACK); 

    int sizeW = width/7; 
    int sizeH = height/7; 

    for (int i = 0; i < 8; i++) { 
     c.drawLine(i*sizeW, 0, i*sizeW, height, p); 
     c.drawLine(0, i*sizeH, width, i*sizeH, p); 
    } 

    backgroudn.setImageBitmap(bm); 
} 

回答

0

我发现错误只是因为高度和宽度为0.但仍然需要这些值,我该怎么办?

这里是我的XML代码:

<ImageView 
    android:id="@+id/ivbackground" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_column="0" 
    android:layout_gravity="left|center_vertical" 
    android:layout_alignParentTop="true" 
    android:layout_marginTop="44dp" 
    android:layout_row="0" />