Android:如何重绘图形元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1017853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:36:27  来源:igfitidea点击:

Android: How to redraw a graphic element?

androiduser-interfacerefresh

提问by Niko Gamulin

I have created a class RoundIcon which extends View and the class contains setIconImage() method:

我创建了一个扩展 View 的类 RoundIcon 并且该类包含 setIconImage() 方法:

public void setIconImage(int imageFromResources) {
    iconImage = BitmapFactory.decodeResource(getResources(), imageFromResources);
    iconWidth = iconImage.getWidth();
    iconHeight = iconImage.getHeight();
    refreshDrawableState();
}

and there is a method onDraw():

并且有一个方法 onDraw():

@Override
protected void onDraw(Canvas canvas) {

    if(px == 0 || py == 0)
    {
        px = 50;
        py = 50;
    }


    canvas.drawCircle(px, py, circleRadius, circlePaint);
    canvas.save();

    if(iconImage != null)
    {
        int cardinalX = px - iconWidth/2;
        int cardinalY = py - iconHeight/2;
        canvas.drawBitmap(iconImage, cardinalX, cardinalY, iconPaint);
    }

    canvas.restore();
}

The problem is that the function onDraw() doesn't execute each time the method setIconImage() is called from main activity and therefore the icon doesn't change in the user interface.

问题是每次从主活动调用方法 setIconImage() 时,函数 onDraw() 都不会执行,因此图标不会在用户界面中更改。

Does anyone know how to modify the code in order to redraw an image every time the method setIconImage is called?

有谁知道如何修改代码以在每次调用 setIconImage 方法时重新绘制图像?

回答by snctln

Try calling View.invalidate()instead of View.refreshDrawableState()

尝试调用View.invalidate()而不是View.refreshDrawableState()

Invalidate will tell the view that all of the pixels in the view need to be redrawn, if you are only updating a smaller area of the view look into the invalidate(Rect) overload for a performance boost.

Invalidate 将告诉视图视图中的所有像素都需要重绘,如果您只是更新视图的较小区域,请查看 invalidate(Rect) 重载以提高性能。

回答by hacken

Definitely call invalidate instead of refreshDrawableState(). You might want to check what thread your on and if on a background call postInvalidate().

绝对调用 invalidate 而不是 refreshDrawableState()。您可能想要检查您在哪个线程上以及是否在后台调用 postInvalidate()。