Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 自訂 View 實作:在 ImageView 上疊加透明圓弧與弧線文字

專案需求要在 ImageView 上疊一層半透明圓弧,並沿著弧線方向排布文字。最直覺的解法是自訂一個 ImageView,在 onDraw() 裡把圓弧與文字畫上去。由於圓弧位置要能任意擺放,顏色、透明度、文字大小與顏色也都得可調,因此額外開了一批自訂屬性。

一、自訂 ArcImageView

設計上先定義一組預設值,再透過 attrs.xml 讓外部覆寫。核心邏輯是:依「圓弧要貼在哪個角」決定圆心與起止角度,畫出弧線,再用同一個 RectF 建立 Path,把文字沿路徑繪製。

public class ArcImageView extends ImageView {

    private final float DEFAULT_TEXT_SIZE = 20;
    private final float DEFAULT_SCALE = 0.5f;      // 決定弧的寬度比例
    private final int DEFAULT_ARC_ALPHA = 100;
    private final int DEFAULT_ARC_WIDTH = 160;
    private final int DEFAULT_START_ANGLE = 180;
    private final int DEFAULT_SWEEP_ANGLE = 90;
    private final int DEFAULT_H_OFFSET = 100;
    private final int DEFAULT_V_OFFSET = 20;

    private String mDrawStr;      // 沿弧線顯示的文字
    private float mTextSize = DEFAULT_TEXT_SIZE;
    private float mScale = DEFAULT_SCALE;
    private int mArcAlpha = DEFAULT_ARC_ALPHA;
    private int mArcWidth = DEFAULT_ARC_WIDTH;
    private int mStartAngle = DEFAULT_START_ANGLE;
    private int mSweepAngle = DEFAULT_SWEEP_ANGLE;
    private float mHOffset = DEFAULT_H_OFFSET;
    private float mVOffset = DEFAULT_V_OFFSET;
    private int mDrawStyle;       // 0~4 對應左上、左下、右上、右下、正中
    private int mArcColor;
    private int mTextColor;

    public ArcImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        obtainAttributes(attrs);
    }

    public void setDrawStr(String drawStr) {
        this.mDrawStr = drawStr;
        invalidate();          // 變更後記得刷新
    }

    public void setArcAlpha(int alpha) {
        this.mArcAlpha = alpha;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 畫圓弧
        Paint arcPaint = new Paint();
        arcPaint.setStrokeWidth(mArcWidth);
        arcPaint.setStyle(Paint.Style.STROKE);
        arcPaint.setColor(mArcColor);
        arcPaint.setAlpha(mArcAlpha);

        int width = getWidth(), height = getHeight();
        float radius = mScale * (width > height ? height : width);

        int center_x = width, center_y = height;
        switch (mDrawStyle) {
            case 0: center_x = 0;         center_y = 0;         mStartAngle = 90;  mSweepAngle = -90; break;
            case 1: center_x = 0;         center_y = height;    mStartAngle = 270; mSweepAngle = 90;  break;
            case 2: center_x = width;     center_y = 0;         mStartAngle = 180; mSweepAngle = -90; break;
            case 3: center_x = width;     center_y = height;    mStartAngle = 180; mSweepAngle = 90;  break;
            case 4: center_x = width / 2; center_y = height / 2; mStartAngle = 270; mSweepAngle = 90;  break;
        }

        RectF oval = new RectF(center_x - radius, center_y - radius,
                               center_x + radius, center_y + radius);
        canvas.drawArc(oval, mStartAngle, mSweepAngle, false, arcPaint);

        // 沿同一條弧線畫文字
        Paint textPaint = new Paint();
        textPaint.setTextSize(mTextSize);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setColor(mTextColor);

        Path path = new Path();
        path.addArc(oval, mStartAngle, mSweepAngle);
        canvas.drawTextOnPath(mDrawStr, path, mHOffset, mVOffset, textPaint);
    }

    private void obtainAttributes(AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.ArcImageView);
        mDrawStr    = ta.getString(R.styleable.ArcImageView_drawStr);
        mTextSize   = ta.getDimension(R.styleable.ArcImageView_textSize, DEFAULT_TEXT_SIZE);
        mArcAlpha   = ta.getInteger(R.styleable.ArcImageView_arcAlpha, DEFAULT_ARC_ALPHA);
        mArcWidth   = ta.getInteger(R.styleable.ArcImageView_arcWidth, DEFAULT_ARC_WIDTH);
        mStartAngle = ta.getInteger(R.styleable.ArcImageView_startAngle, DEFAULT_START_ANGLE);
        mSweepAngle = ta.getInteger(R.styleable.ArcImageView_sweepAngle, DEFAULT_SWEEP_ANGLE);
        mHOffset    = ta.getInteger(R.styleable.ArcImageView_hOffset, DEFAULT_H_OFFSET);
        mVOffset    = ta.getInteger(R.styleable.ArcImageView_vOffset, DEFAULT_V_OFFSET);
        mArcColor   = ta.getColor(R.styleable.ArcImageView_arcColor, 0XCCCCCC);
        mTextColor  = ta.getColor(R.styleable.ArcImageView_textColor, 0XFFFFFF);
        mDrawStyle  = ta.getInt(R.styleable.ArcImageView_drawStyle, 0);
        ta.recycle();
    }
}

二、attrs.xml 宣告屬性

<resources>
    <declare-styleable name="ArcImageView">
        <attr name="drawStr" format="string" />
        <attr name="textSize" format="dimension" />
        <attr name="arcAlpha" format="integer" />
        <attr name="arcWidth" format="integer" />
        <attr name="startAngle" format="integer" />
        <attr name="sweepAngle" format="integer" />
        <attr name="scale" format="float" />
        <attr name="hOffset" format="float" />
        <attr name="vOffset" format="float" />
        <attr name="drawStyle" format="enum">
            <enum name="LEFT_TOP" value="0" />
            <enum name="LEFT_BOTTOM" value="1" />
            <enum name="RIGHT_TOP" value="2" />
            <enum name="RIGHT_BOTTOM" value="3" />
            <enum name="CENTER" value="4" />
        </attr>
        <attr name="arcColor" format="color" />
        <attr name="textColor" format="color" />
    </declare-styleable>
</resources>

三、版面配置中引用

使用自訂屬性前,根節點必須加上命名空間宣告:

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res-auto"
    ... >

    <com.linuxidc.customviewsdemo.views.ArcImageView.ArcImageView
        android:id="@+id/aiv_one"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/steak"
        custom:drawStr="牛排"
        custom:arcAlpha="100"
        custom:arcColor="@color/gray"
        custom:textColor="@color/black"
        custom:textSize="20sp" />
</LinearLayout>

少了 xmlns:custom="https://schemas.android.com/apk/res-auto" 這行,自訂屬性會直接編譯失敗,這是最常踩的坑。

四、Activity 中動態切換

aiv_one = findViewById(R.id.aiv_one);
aiv_one.setArcAlpha(180);

btn_another_one.setOnClickListener(v -> {
    if (mGroup == 1) {
        aiv_one.setDrawStr("蘋果");   aiv_one.setBackgroundResource(R.drawable.apple);
        aiv_two.setDrawStr("柚子");   aiv_two.setBackgroundResource(R.drawable.pineapple);
        mGroup = 2;
    } else {
        aiv_one.setDrawStr("牛排");   aiv_one.setBackgroundResource(R.drawable.steak);
        aiv_two.setDrawStr("海鮮");   aiv_two.setBackgroundResource(R.drawable.seafood);
        mGroup = 1;
    }
});

因為 setter 內部呼叫了 invalidate(),文字與透明度會立即重繪,不必手動刷新。

心得

自訂 View 的套路其實很固定:重寫 onMeasure()、onLayout()、onDraw() 完成測量與繪製,繪製時離不開 Canvas、Paint、Path、Bitmap 這幾個類別。整個過程就是把現實中的畫板、畫紙、畫筆與作畫動作,用物件導向的方式描述一遍。掌握 drawArc 與 drawTextOnPath 這對組合,弧線文字之類的需求都能迎刃而解。

Copyright © Linux教程網 All Rights Reserved