强制重绘自定义视图(android)

时间:2014-06-14 22:13:31

标签: android canvas

我刚读过类似的问题,但所有答案对我都不起作用。

我有这个自定义视图:

public class CompassTargetView extends View {

Context mContext;
Bitmap mBmp;

Matrix matrix;

int w, h, bw, bh;
int px = -1, py = -1;


public CompassTargetView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setWillNotDraw(false);

    mContext = context;

    Resources res = getResources();
    mBmp = BitmapFactory.decodeResource(res, R.drawable.ttriangle);
    bw = mBmp.getWidth();
    bh = mBmp.getHeight();
}

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

    if(px == -1 && py == -1){
        px=w/2-bw/2;
        py=h/2-bh/2;
    }


    if (matrix != null) {
        canvas.drawBitmap(mBmp, matrix, null);
        matrix = null;
    } else {
        canvas.drawBitmap(mBmp, px, py, null);
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //registriamo le dimensioni della view
    w = MeasureSpec.getSize(widthMeasureSpec);
    h = MeasureSpec.getSize(heightMeasureSpec);
    setMeasuredDimension(w, h);
}

public void setTrinagleIcon(){
    Resources res = getResources();
    mBmp = BitmapFactory.decodeResource(res, R.drawable.ttriangle);
    bw = mBmp.getWidth();
    bh = mBmp.getHeight();
    invalidate();
}

public void setCircleIcon(){
    Resources res = getResources();
    mBmp = BitmapFactory.decodeResource(res, R.drawable.tcircle);
    bw = mBmp.getWidth();
    bh = mBmp.getHeight();
    invalidate();
}

public void setXY(Integer nx, Integer ny){
    px = nx - bw/2;
    py = ny - bh/2;
    invalidate();
}

public void translateIcon(Integer nx, Integer ny){
    matrix = new Matrix();
    matrix.reset();
    matrix.postTranslate(nx, ny);
    invalidate();
}

public void rotateIcon(Integer nx, Integer ny, Float ang){
    matrix = new Matrix();
    matrix.reset();
    matrix.postRotate(ang, nx, ny);
    invalidate();
}

}

它显示一个小图标,然后我想使用setXY,translateIcon和rotateIcon来“动画”图标。但是,如果我调用setXY,则onDraw方法仅在视图创建之后调用,而不调用translateIcon和rotateIcon onDraw。

我只使用invalidate();我试过setWillNotDraw(false);但这不起作用。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在onDraw中显示Toast是一个非常糟糕的主意,因为它可能会导致调用onDraw,它将显示Toast,它将调用onDraw ....无限循环。

所以用日志替换Toast(并且只在调试期间保留日志,因为onDraw经常被调用)并查看附加内容。


问题是您没有更新成员矩阵。你正在创建一个新的!

public void translateIcon(Integer nx, Integer ny){
    Matrix matrix = new Matrix();  // <-- WRONG
    matrix = new Matrix(); // <-- CORRECT
    ...
    invalidate();
}
相关问题