Android自定义View练习,文字圆环排列的TextView,可旋转

控件:

/**
 * 字圆形排列
 * Created by ruin on 2017/3/14.
 */
public class CircleTextView extends View {

    private Paint paint;
    private String mText;
    private int mTextColor, mTextSize, radius, angle = 0;

    public CircleTextView(Context context) {
        this(context, null);
    }

    public CircleTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleTextView, defStyleAttr, 0);
        mText = a.getString(R.styleable.CircleTextView_mText);
        mTextColor = a.getColor(R.styleable.CircleTextView_mTextColor, Color.BLACK);
        mTextSize = (int) a.getDimension(R.styleable.CircleTextView_mTextSize, 50);
        radius = (int) a.getDimension(R.styleable.CircleTextView_radius, mTextSize);
        a.recycle();
    }

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

        paint = new Paint();
        paint.setColor(mTextColor);
        paint.setTextSize(mTextSize);
        // 绘文字
        if (!TextUtils.isEmpty(mText)) {
            char[] chars = mText.toCharArray();

            for (int i = 0; i < chars.length; i++) {
                canvas.save();

                canvas.rotate(360 / chars.length * i + angle, getWidth() / 2, getHeight() / 2);
                canvas.drawText(chars[i] + "", getWidth() / 2 - 21, radius, paint);
                canvas.restore();
            }

            //下列代码控制是否旋转,当然,用动画更好控制,我这是省懒事了。罪过
//            angle += 1;
//            if (angle == 360) {
//                angle = 0;
//            }
//            invalidate();
        }
    }
}

res/values下attrs.xml中添加:

<declare-styleable name="CircleTextView">
        <attr name="mText" format="string"/>
        <attr name="mTextColor" format="color"/>
        <attr name="mTextSize" format="dimension"/>
        <attr name="radius" format="dimension"/>
    declare-styleable>

调用:

android:id="@+id/animation_ctv"
android:layout_width="200dp"
android:layout_height="200dp"
app:mText="转转转转转转转"
app:mTextSize="30sp"
/>

效果
Android自定义View练习,文字圆环排列的TextView,可旋转_第1张图片

你可能感兴趣的:(Android自定义控件)