CustomView 效能提示

不要在 onDraw 中分配新物件 ****

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint paint = new Paint(); //Do not allocate here
}

而不是在畫布中繪製 drawable …


``` placeholder
drawable.setBounds(boundsRect);

drawable.draw(canvas);
```

使用點陣圖可以更快地繪製:

``` placeholder
canvas.drawBitmap(bitmap, srcRect, boundsRect, paint);
```

不要重繪整個檢視以僅更新其中的一小部分。而是重繪檢視的特定部分。

``` placeholder
invalidate(boundToBeRefreshed);
```

如果你的檢視正在進行一些連續動畫,例如顯示每一秒的監視面,至少會停止活動的 `onStop()` 處的動畫並將其重新啟動到活動的 `onStart()` 上。

不要在檢視的 `onDraw` 方法中進行任何計算,而應該在呼叫 `invalidate()` 之前完成繪圖。通過使用此技術,你可以避免在檢視中丟幀。

## 旋轉

檢視的基本操作是翻譯,旋轉等...當他們在自定義檢視中使用點陣圖或漸變時,幾乎每個開發人員都遇到了這個問題。如果檢視將顯示旋轉檢視並且點陣圖必須在該自定義檢視中旋轉,我們中的許多人會認為它會很昂貴。許多人認為旋轉點陣圖非常昂貴,因為要做到這一點,你需要翻譯點陣圖的畫素矩陣。但事實是,它並不那麼艱難! 而不是旋轉點陣圖,只需旋轉畫布本身!

``` placeholder
// Save the canvas state
int save = canvas.save();
// Rotate the canvas by providing the  center point as pivot and angle
canvas.rotate(pivotX, pivotY, angle);
// Draw whatever you want
// Basically whatever you draw here will be drawn as per the angle you rotated the canvas
canvas.drawBitmap(...);
// Now restore your your canvas to its original state
canvas.restore(save);
// Unless canvas is restored to its original state, further draw will also be rotated.
```