2

私は LinearLayout を拡張しています:

public class MyLinearLayout extends LinearLayout {
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint paint = new Paint();
        paint.setColor(0xFFFF0000);
        canvas.drawLine(0, 0, getWidth(), getHeight(), paint);
    }
}

レイアウトに子要素がある場合、上の赤い線はそれらの上に描画されるべきではありませんか? 次のようなレイアウトを検討します。

<MyLinearLayout>
    <ImageView />
</MyLinearLayout>

子ImageViewの上に赤い線が引かれることを期待しています。しかし、それはその下に描画されます。super.onDraw() 行が終了した後、すべての子の描画が完了すると想定していました。

すべての子の描画が完了した後、キャンバスにアクセスして何かを描画する方法はありますか?

ありがとう

4

3 に答える 3

11

を呼び出さない限り、レイアウトは描画されませんsetWillNotDraw(false);。彼らは効率上の理由からそれを行います。

編集

onDraw()Canvas実際には、描画操作が発生する前に を変更できるようにすることを目的としています。実際には描きません。あなたがしたいことはdraw()、次のようにオーバーライドすることです:

@Override
protected void draw(Canvas canvas) {
    super.draw(canvas);

    Paint paint = new Paint();
    paint.setColor(0xFFFF0000);
    canvas.drawLine(0, 0, getWidth(), getHeight(), paint);
}

スーパーを呼び出すと、すべての子がビューに描画されます。次に、すべての線を描画します。私はまだあなたsetWillNotDraw(false)が呼ばれる必要があると信じています。

于 2012-05-23T20:24:35.540 に答える
0

I'm rewriting my answer as I hadn't seen your line of code where you were drawing to the canvas.

The canvas like some other graphics environments is inverted. So calling getHeight() is actually drawing the line at the bottom. Instead call

   canvas.drawLine( 0, 0, getWidth(), 0, paint);

This means draw the line at the top, across the width of the view.

Also, calling super first paints the children prior to any custom painting so your fine there.

于 2014-10-20T16:16:31.963 に答える