TextView中文字傾斜
需求:使TextView中的文字傾斜一定的角度。如下圖所示:

如何實現呢?自定義View?這可能是大多數同學產生的第一個想法。的確,自定義View可以實現這個需求。我也找過網上自定義view的方法,大多數只是繼承TextView,在onDraw()方法中將畫布旋轉:
@Override protected void onDraw(Canvas canvas) { canvas.save(); canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop()); canvas.rotate(degrees, this.getWidth() / 2f, this.getHeight() / 2f); //canvas.rotate(degrees, 0, 0); super.onDraw(canvas); canvas.restore(); }
其中 canvas.rotate(degrees, this.getWidth() / 2f, this.getHeight() / 2f);
方法中 degrees
就是需要旋轉的角度。
今天介紹一種更簡單的方法:
View中有一個屬性: rotation
,可以實現旋轉View。因為TextView是繼承的View,所以也可以使用這個屬性。
XML中設定
android:rotation="45"
java程式碼中設定
mTextView.setRotation(45);
View的相關原始碼:
/** * Sets the degrees that the view is rotated around the pivot point. Increasing values *設定檢視圍繞軸心點旋轉的度數。 * result in clockwise rotation. *順時針旋轉 * @param rotation The degrees of rotation.旋轉的角度。 * @see #getRotation() * @see #getPivotX() * @see #getPivotY() * @see #setRotationX(float) * @see #setRotationY(float) * * @attr ref android.R.styleable#View_rotation */ public void setRotation(float rotation) { if (rotation != getRotation()) { // Double-invalidation is necessary to capture view's old and new areas invalidateViewProperty(true, false); mRenderNode.setRotation(rotation); invalidateViewProperty(false, true); invalidateParentIfNeededAndWasQuickRejected(); notifySubtreeAccessibilityStateChangedIfNeeded(); } }
其實,其他繼承View的控制元件都可以使用這個屬性進行旋轉。並不影響自身的點選事件。