Android的:如何重绘图形元素?元素、Android

2023-09-05 10:11:29 作者:被淹死的鱼

我创建了一个类RoundIcon延伸查看和类包含setIconImage()方法:

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

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

和有这样一种方法的OnDraw():

and there is a method 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();
}

的问题是,该函数的OnDraw()不执行每次方法setIconImage()从主要活动被称为和因此的图标不会在用户界面改变

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.

有谁知道如何修改code,以每一个方法setIconImage被调用时重绘的图像?

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

推荐答案

尝试调用View.invalidate()代替View.refreshDrawableState()

的Invalidate会告诉认为,所有在视图中的像素都需要重绘,如果你只更新的角度看一个较小的区域进入无效(矩形)过载性能的提升。

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.