绘制视图和所有它的孩子

问题描述 投票:12回答:2

我正在尝试将视觉效果应用于视图组。我的想法是获取视图组的位图,缩小它,将其重新展开,然后在视图组上绘制它,使其具有块状,低质量的效果。

我使用这段代码的大部分方式都是:

public class Blocker {

    private static final float RESAMPLE_QUALITY = 0.66f; // less than 1, lower = worse quality


    public static void block(Canvas canvas, Bitmap bitmap_old) {
        block(canvas, bitmap_old, RESAMPLE_QUALITY);
    }


    public static void block(Canvas canvas, Bitmap bitmap_old, float quality) {
        Bitmap bitmap_new = Bitmap.createScaledBitmap(bitmap_old, Math.round(bitmap_old.getWidth() * RESAMPLE_QUALITY), Math.round(bitmap_old.getHeight() * RESAMPLE_QUALITY), true);
        Rect from = new Rect(0, 0, bitmap_new.getWidth(), bitmap_new.getHeight());
        RectF to = new RectF(0, 0, bitmap_old.getWidth(), bitmap_old.getHeight());
        canvas.drawBitmap(bitmap_new, from, to, null);
    }
}

我只是传递画布来绘制和一个需要按比例缩小+向上的位图,它运行良好。

public class BlockedLinearLayout extends LinearLayout {

    private static final String TAG = BlockedLinearLayout.class.getSimpleName();


    public BlockedLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        applyCustomAttributes(context, attrs);
        setup();
    }


    public BlockedLinearLayout(Context context) {
        super(context);
        setup();
    }


    private void setup() {
        this.setDrawingCacheEnabled(true);
    }


    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        // block(canvas); If I call this here, it works but no updates
    }


    @Override
    public void onDraw(Canvas canvas) {
        // block(canvas); If I call this here, draws behind children, still no updates
    }

    private void block(Canvas canvas) {
        Blocker.block(canvas, this.getDrawingCache());
    }
}

我遇到的问题是在我的视图组中。如果我在视图组的绘图中运行块方法,它会覆盖所有内容,但在子视图更改时不会更新。我用Log跟踪函数调用,并且draw方法似乎正在运行,但没有任何变化。

我也试过在onDraw中实现它。这会在所有子视图后面绘制位图,并且它们也不会更新。

任何人都可以解释我将如何解决这个问题?

android android-canvas android-view
2个回答
40
投票

试试这个:

@Override
protected void dispatchDraw(Canvas canvas) {
    // call block() here if you want to draw behind children
    super.dispatchDraw(canvas);
    // call block() here if you want to draw over children
}

并在每次更改子项时调用destroyDrawingCache()然后调用buildDrawingCache()。


0
投票

Draw()方法适合你。

我现在正试图将计时时间视图设置为圆形,当时间过去时,视图将减小其角度。它用于覆盖个人资料照片(圆形照片)。

© www.soinside.com 2019 - 2024. All rights reserved.