这是我的OnDraw()方法
void onDraw(Canvas canvas) {
mCanvas = canvas;
//invalidate();
int x = 0;
Iterator<Letter> it = mNextUpQueue.iterator();
while(it.hasNext()){
mCanvas.drawBitmap(it.next().getNext(), mNextUpCoordinates.get(x).x, mNextUpCoordinates.get(x).y, mPaint);
mCanvas.drawBitmap(mAvailableLetters.get(x).getNotPressed(), mAvailableLettersCoordinates.get(x).x, mAvailableLettersCoordinates.get(x).y, mPaint);
x++;
}
}
我已将canvas设置为全局变量mCanvas。但是,如果我尝试从onDraw()方法外部绘制mCanvas,我会收到错误。是因为我做错了什么还是必须始终在onDraw方法中使用画布?
答案 0 :(得分:7)
您不得参考传递的Canvas,因为它仅在onDraw(Canvas)
方法调用期间有效。
我建议彻底阅读http://developer.android.com/guide/topics/graphics/2d-graphics.html#draw-with-canvas,可能的解释方法很好:
onDraw(Canvas)
方法提供的Canvas。这是在UI线程中完成的,所以不应该在这里尝试任何复杂的onDraw(Canvas)
方法的Canvas lockCanvas()
方法从中获取Canvas对象。答案 1 :(得分:1)
您可以使用invalidate();
来调用onDraw()
并根据绘图逻辑绘制画布。
示例强>
public class ThumbnailImage extends android.support.v7.widget.AppCompatImageView {
public static final int FALSE = 0, TRUE = 1, NOT_SET = 2;
private int drawingStatus;
public ThumbnailImage(Context context) {
super(context);
init();
}
public ThumbnailImage(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public ThumbnailImage(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
...
drawingStatus = NOT_SET;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (drawingStatus != NOT_SET) {
if (drawingStatus == TRUE) {
...
} else {
...
}
}
}
public void setDrawingStatus(int drawingStatus) {
this.drawingStatus = drawingStatus;
invalidate();
}
}