哇,這是令人沮喪的。我真的只是試圖在每次畫畫前清除我的ImageView
。從以前的onDraw調用ImageView中恢復畫布
我試圖將Android的ImageView
類擴展爲自定義StatusBarImageView
。我提供了一個公共方法setPercentComplete(float percent)
,以便我的活動可以相應地更新圖像。但是,每次嘗試通過使圖像失效並觸發它的方法來更新圖像時,出於某種原因,它會嘗試在現有圖像上繪製新狀態欄及其文本,而不是重新開始。所以我使用canvas.drawText(...)
繪製的字幕互相流血。
任何人都可以告訴我爲什麼發生這種情況/如何解決它?
我試過了幾種不同的方法,但都沒有工作。
我試圖拯救我第一次在繪製之前和以後每次之前恢復,但顯然它的每一次新的畫布onDraw()
方法火災,所以restore()
拋出一個異常,有一直沒有save()
。
我試過使用canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
,但不僅如此,它會將背景由於某種原因更改爲純黑色。
這裏是我的代碼:
class StatusBarImageView extends ImageView {
private float status = 100.0f;
private Canvas lastCanvas;
private Paint imagePainter = new Paint();
private Paint textPainter = new Paint();
public StatusBarImageView(Context context) {
super(context);
initializePainters();
}
public StatusBarImageView(Context context, AttributeSet attributes) {
super(context, attributes);
initializePainters();
}
public StatusBarImageView(Context context, AttributeSet attributes, int defStyle) {
super(context, attributes, defStyle);
initializePainters();
}
private void initializePainters() {
this.status = 100.0f;
this.imagePainter.setStyle(Style.FILL_AND_STROKE);
this.textPainter.setStyle(Style.FILL);
this.textPainter.setFakeBoldText(true);
}
public void setPercentComplete(float status) {
this.status = status;
this.invalidate();
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Erase previous status bar and its text captions before drawing new one
if(this.lastCanvas != null) {
this.lastCanvas.restore(); //throws exception
//this.lastCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); // Doesn't work and makes background black
}
canvas.save();
this.lastCanvas = canvas;
//this.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); // Doesn't work and makes the background black
//this.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.MULTIPLY); // Same problem
this.drawStatusBarAndCaptions(canvas); //Uses canvas.drawRect and canvas.drawText
}
//...
}
而且xml
只是看起來像:
<my.package.name.then.StatusBarImageView
android:id="@+id/status_bar"
android:layout_width="match_parent"
android:layout_height="0dp"
android:padding="0dp"
android:layout_margin="0dp"
android:layout_weight="3"/>
每次'的onDraw()'運行,你」重新傳遞了一個新的「空白」Canvas。沒有必要嘗試清除之前的抽獎,或者在那裏進行保存/恢復舞蹈。只需使用當前值繪製你的東西。 –
嗯......也許'畫家'類變量是我的問題?我試圖抹去以前的抽籤的唯一原因,是因爲他們出於某種原因而堅持。我的新圖紙只是添加在他們之上。也許我每次都必須使用新的Painter對象? – SnoopDougg
那麼,'Paint'對象不會那樣做。你是否設置了「ImageView」的圖像? 'drawStatusBarAndCaptions()'做了什麼,到底是什麼? –