Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義 TextView:讓文字傾斜(RotateTextView)

編輯:關於 Android 程式設計

系統內建的控件不一定能滿足所有設計需求。舉例來說,需要讓 TextView 裡的文字傾斜一個角度時,就必須自己寫一個子類別,在 onDraw 之前把 Canvas 旋轉一下。

自定義 RotateTextView

package com.leigo.ratatetextview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

/**
 * 可旋轉的 TextView
 */
public class RotateTextView extends TextView {

    private static final int DEFAULT_DEGREES = 0;
    private int mDegrees;

    public RotateTextView(Context context) {
        super(context, null);
    }

    public RotateTextView(Context context, AttributeSet attrs) {
        super(context, attrs, android.R.attr.textViewStyle);
        this.setGravity(Gravity.CENTER);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RotateTextView);
        mDegrees = a.getDimensionPixelSize(R.styleable.RotateTextView_degree, DEFAULT_DEGREES);
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
        //以檢視中心為軸心旋轉
        canvas.rotate(mDegrees, this.getWidth() / 2f, this.getHeight() / 2f);
        super.onDraw(canvas);
        canvas.restore();
    }

    public void setDegrees(int degrees) {
        mDegrees = degrees;
    }
}

關鍵在 onDraw:先 save() 保存畫布狀態,旋轉後畫完再 restore() 還原,避免影響到同一層的其他元件。旋轉的軸心刻意設為檢視中心,這樣文字才會繞著自己轉,而不是被甩到畫面外。

宣告自定義屬性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RotateTextView">
        <attr name="degree" format="dimension" />
    </declare-styleable>
</resources>

使用方式

1. 版面檔中直接使用:

<com.leigo.ratatetextview.RotateTextView
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:id="@+id/text"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:padding="10dp"
    android:text="@string/hello_world"
    app:degree="10dp" />

2. 或在程式碼中動態設定:

RotateTextView mText = (RotateTextView) findViewById(R.id.text);
mText.setDegrees(10);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved