Here's my OnDraw() method
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++;
}
}
I have set canvas to a global variable mCanvas. But if I try to paint on mCanvas from outside the onDraw() method I get an error. Is it because I'm doing something wrong or the canvas must always be used from within the onDraw method?
You mustn't take the reference to the Canvas passed, as it is only valid during the onDraw(Canvas)
method call.
I recommend reading http://developer.android.com/guide/topics/graphics/2d-graphics.html#draw-with-canvas thoroughly, the possible ways are explained there quite well:
onDraw(Canvas)
method, during this method call. This is done in the UI thread, so nothing complicated should be attempted hereonDraw(Canvas)
methodlockCanvas()
method.You can use invalidate();
to call onDraw()
and draw canvas depending on your drawing logic.
Example
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With