编程知识 cdmana.com

Android font set to medium

Android TextView There are only three states to set font thickness ,textStyle The value is only bold、nomral、italic、 Customer demand is that the font is medium thickness , only because ios Yes, there is medium attribute ,Android Be asked for the same ;

To achieve this , We can do it in a different way , Since there is no medium, Then change Paint Width , That is, the width of the brush , It's equivalent to changing the thickness of the font , And more flexible , You can adjust the width freely ; Use setStrokeWidth(num) The method can

It's also very simple to implement , as follows :

For the realization of a single

TextView tvTitle = findViewById(R.id.title);

TextPaint  tp = tvTitle.getPaint();

tp.setStrokeWidth(1.0f)

setStrokeWidth() Method needs to pass in a float value , The greater the numerical , The thicker the font is ,0.0f Represents the width of a regular brush , Equivalent to the default .

The global implementation is

Inherit TextView that will do , stay onDraw Method setStrokeWidth() The method can , The width is freely controllable , The code is as follows :

public class MediumBoldTextView extends TextView {
    private float mStrokeWidth = 0.9f;

    public MediumBoldTextView(Context context) {
        super(context);
    }

    public MediumBoldTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MediumBoldTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MediumBold_TextView,defStyleAttr,0);
        mStrokeWidth = array.getFloat(R.styleable.MediumBold_TextView_strokeWidth,mStrokeWidth);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        // Get the brush of the current control 
        TextPaint paint = getPaint();
        // Set the stroke width value of the brush 
        paint.setStrokeWidth(mStrokeWidth);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        super.onDraw(canvas);
    }
}

R.styleable.MediumBold_TextView stay attrs.xml Under the document :

So it can be used directly in the layout , And then by setting strokeWidth You can change the width freely .

 

版权声明
本文为[osc_ m3eztdrr]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224102713669y.html

Scroll to Top