2013-07-01 37 views
1

我有我自己的视图子类,布局(我称之为ViewGallery),我的问题是,我手动绘制的视图不会出现在屏幕上,这里是onDraw方法。绘制子视图

@Override 
protected void onDraw(Canvas canvas) { 
    for(Child child : visibleChilds){ 
     canvas.save(); 
     canvas.clipRect(child.bounds); 
     child.view.draw(canvas); 
     canvas.restore(); 
    } 
} 

private List<Child> visibleChilds = new ArrayList<ViewGallery.Child>(); 

private static class Child { 
    private View view; 
    private Rect bounds; 

    public Child(View view, Rect rect) { 
     this.view = view; 
     bounds = rect; 
    } 
} 

据我所知,应该在指定的剪切Canvas中绘制内部视图。

为什么视图仍然是空的?

此外,我试图扩展ViewGroup,所以我将自己作为参数传递给适配器,但默认ViewGroup.LayoutParams没有留下(或x)属性,我需要妥善处理视图的转换。但是,在继承onDraw时,onDraw永远不会被调用,孩子仍然不会出现。

+0

您需要重写dispatchDraw()来绘制子元素,而不是onDraw()。你可以从onDraw()做到,但你首先需要调用setWillNotDraw(false)。您还应该使用ViewGroup.drawChild()来正确绘制每个孩子。 –

+0

有没有dispatchDraw重写在ViewGroup,我试图使用setWillNotDraw方法。另外,我需要知道ViewGroup是否会处理addViews,还是我应该重写它呢? –

+0

是的,有一个dispatchDraw()方法:http://developer.android.com/reference/android/view/ViewGroup.html#dispatchDraw(android.graphics.Canvas) –

回答

0

我不确定我是否正确理解问题。 但是,如果您试图在画布上绘制视图,则必须启用图形缓存,从中获取位图并绘制该图。

例如:

  // you have to enable setDrawingCacheEnabled, or the getDrawingCache will return null 
      view.setDrawingCacheEnabled(true); 

      // we need to setup how big the view should be..which is exactly as big as the canvas 
      view.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.AT_MOST)); 
      // assign the layout values to the textview 
      view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 


      mBitmap = view.getDrawingCache(); 
      canvas.drawBitmap(mBitmap, x, y, mPaint); 
      // disable drawing cache 
      view.setDrawingCacheEnabled(false); 

Ofcourse在这种情况下它会只是在给定的位置绘制的视图的位图。