Android 倾斜文字 效果设置

有时候Android自带的控件无法满足我们的某些要求,这时就需要我们自定义控件来实现这些功能。比如需要一个TextView里的字倾斜一定的角度,就需要自定义TextView。


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.Gravity;
import com.example.yikezhong.R;

/**
 * 自定义 倾斜字体 TextView
 */
public class RotateTextView extends android.support.v7.widget.AppCompatTextView {

    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;
    }

}
自定义attrs.xml文件 属性
[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <declare-styleable name="RotateTextView">  
  4.         <attr name="degree" format="dimension" />  
  5.     </declare-styleable>  
  6. </resources>  

用法:

1.xml

<自己的包名类名全路径
    android:id="@+id/text"
    android:text="神评!"
    app:degree="10dp"
    android:textSize="25sp"
    android:textColor="#616161"
    android:layout_marginLeft="6dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true" />
2. java
[java]  view plain  copy
  1. RotateTextView  mText = (RotateTextView) findViewById (R.id.text);  
  2. mText.setDegrees(10);

适配器中设置:

  1. RotateTextView  text = (RotateTextView) findViewById (R.id.text);  

//设置倾斜字体显示 神评
holder.text.setDegrees(28);


项目地址:

https://coding.net/u/leigo/p/RotateTextView/git



猜你喜欢

转载自blog.csdn.net/it666dhw/article/details/80627276