美文网首页
android:自定义可倾斜任意角度的TextView控件

android:自定义可倾斜任意角度的TextView控件

作者: 江左灬梅郎 | 来源:发表于2018-08-28 14:49 被阅读0次

最近,项目中需要添加一个优惠券系统的功能,在优惠券界面我们美丽阔爱的UI小姐姐来了这样一个需求:

image.png

其中,具体的优惠金额并不是固定的,而是根据具体业务来变化的。
偷懒,是人类的天性。为了一劳永逸的解决和UI小姐姐的交配问题(哦,不,说错了,是交流问题),我们自然想到了自定义一个可旋转角度的TextView。

代码不多,很简单,直接上代码。

public class LeanTextView extends TextView {
    private int mDegrees;

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

    public LeanTextView(Context context, AttributeSet attrs) {
        super(context, attrs, android.R.attr.textViewStyle);
        this.setGravity(Gravity.CENTER);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LeanTextView);
        mDegrees = a.getDimensionPixelSize(R.styleable.LeanTextView_degree, 0);
        a.recycle();
    }

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

    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
        if (this.getWidth() > this.getHeight()){
            canvas.rotate(mDegrees, this.getWidth() / 2f, this.getWidth() / 2f);
        }else{
            canvas.rotate(mDegrees, this.getHeight() / 2f, this.getHeight() / 2f);
        }

        super.onDraw(canvas);
        canvas.restore();
    }

    public int getDegrees() {
        return mDegrees;
    }

    public void setDegrees(int mDegrees) {
        this.mDegrees = mDegrees;
        invalidate();
    }
}

styleable.xml

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

相关文章

网友评论

      本文标题:android:自定义可倾斜任意角度的TextView控件

      本文链接:https://www.haomeiwen.com/subject/lcofwftx.html