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

最近,项目中需要添加一个优惠券系统的功能,在优惠券界面我们美丽阔爱的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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容