美文网首页
[改造]微信缩放字体view的改造

[改造]微信缩放字体view的改造

作者: 吉凶以情迁 | 来源:发表于2021-09-15 22:54 被阅读0次

网上的代码bug很多,而且不方便控制标准字体,有些代码基本写死的,比如return 0.8+(ratio).....

改造后的效果

可以自定义标准字体所处位置.
可以实时展示最小和最大的文字.
可以自定义标尺总数.
可以自定义位置停留

遇到的问题
公式换算. 我数学以前连个除法都头疼,现在百分比转换搞明白了,宽度转指定的百分比.
比如刻度是10,我就要把宽度的百分比转成刻度里面的百分比,这需要相互转换才能完成我上面所说的改造效果.
关于宽度和进度的转换,用于任意进度停留的还原.


    public static float widthX2Progress(float viewWidth, float currentX, float maxProgress) {


/*        float width=500;
        float current=250;
        float ratio=current/width;// 得到比1小的比例

        float myMaxProgress=15;
        float result=myMaxProgress*ratio;*/

        float ratio = currentX / viewWidth;
        float result = maxProgress * ratio;
        return result;

    }

    public static float progress2Width(float viewWidth, float progress, float maxProgress) {
        float ratio = progress / maxProgress;
        float result = ratio * viewWidth;
        return result;

    }

允许拖动任意位置的设置

 /**
     * 获取最近的刻度
     */
    private PointF getNearestPoint(float x) {
        for (int i = 0; i < points.size(); i++) {
            PointF point = points.get(i);
            if (Math.abs(point.x - x) < itemWidth / 2) {
                if (allowFreeProgerss) {
                    currentProgress = widthX2Progress(width, x, max);
                    return new PointF(x, point.y);
                } else {
                    currentProgress = i;
                    return point;

                }
//                return new PointF((int) x, point.y);
            }
        }
        return null;
    }

关于字体缩放比的转换

   public float getCurrentScaleRatio() {
        return getCurrentScaleRatio(getCurrentProgress());
    }

    public float getCurrentScaleRatio(float currentProgress) {
        if (currentProgress == getStandPosition()) {
            return 1;
        }

        float result = (currentProgress * 1.0f / getStandPosition());//限制最小缩放 0.3但是会导致找不到标准位..
        if (result < 0.2) {
            return 0.2f;
        }
        return result;
    }

    /**
     * @param position          progress
     * @param beforedimensionPx int dimension = getResources().getDimensionPixelSize(R.dimen.sp_stander);
     * @return
     */
    public float getScalefontSizePx(float position, float beforedimensionPx) {
        float fontScaleRatio = getCurrentScaleRatio(position);
        return fontScaleRatio * beforedimensionPx;
//        fontBinding.tvShow.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizeScale * dimension);
    }

/**
 * https://blog.csdn.net/cs_lwb/article/details/87727561
 * TODO 仿微信字体大小调整
 * 自定义属性:
 * lineWidth        线条粗细
 * lineColor        线条颜色
 * totalCount       线条格数
 * circleColor      球型颜色
 * circleRadius     球型颜色半径
 * textFontColor    文字颜色
 * smallSize        小“A” 字体大小
 * standerSize      “标准” 字体大小
 * bigSize          大“A” 字体大小
 * defaultPosition  默认位置
 */
public class FontSizeView extends View {

    private int defaultLineColor = Color.rgb(33, 33, 33);
    private int defaultLineWidth;
    private int defaultMax = 5;
    private int defaultCircleColor = Color.WHITE;
    private int defaultCircleRadius;

    public float getCurrentProgress() {
        return currentProgress;
    }

    // 当前所在位置
    private float currentProgress;

    public float getDefaultProgress() {
        return defaultProgress;
    }


    // 一共有多少格
    private int max = 5;
    // 默认位置
    /**
     * 原始位置在哪里 原始字体
     */
    private float standPosition = 1.2f;//Math.max((max / 2f) - 6, 3f);
    private float defaultProgress = standPosition;

    public float getStandPosition() {
        return standPosition;
    }

    public void setStandPosition(int standPosition) {
        this.standPosition = standPosition;
    }

    // 线条颜色
    private int lineColor = Color.BLACK;
    // 线条粗细
    private int lineWidth;

    //字体颜色
    private int textColor = Color.BLACK;
    //字体大小
    private float smallSize = 10;//这里可以根据 getScalefontSizePx 然后转换为sp得到。
    private int standerSize = 13;
    private int bigSize = 45;

    // 圆半径
    private int circleRadius;
    private int circleColor = Color.WHITE;
    // 一段的宽度,根据总宽度和总格数计算得来
    private int itemWidth;
    // 控件的宽高
    private int height;
    private int width;
    // 画笔
    private Paint mLinePaint;
    private Paint bigFontPaint;
    private Paint smallFontPaint;
    private Paint mText2Paint;
    private Paint mCirclePaint;
    // 滑动过程中x坐标
    private float currentX = 0;
    // 有效数据点
    private List<PointF> points = new ArrayList<>();

    private float circleY;
    private float textbigScaleX;
    private float textsmallScaleX;
    private float text2ScaleX;

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

    public FontSizeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {

        // initDefault
        defaultLineWidth = DensityUtil.dip2px(context, 2);
        defaultCircleRadius = DensityUtil.dip2px(context, 35);
        lineWidth = DensityUtil.dip2px(context, 1);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FontSizeView);
        final int N = typedArray.getIndexCount();
        for (int i = 0; i < N; i++) {
            initCustomAttr(typedArray.getIndex(i), typedArray);
        }
        typedArray.recycle();
        // 初始化画笔
        mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mLinePaint.setColor(lineColor);
        mLinePaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mLinePaint.setStrokeWidth(lineWidth);

        //文字画笔
        bigFontPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bigFontPaint.setColor(textColor);
        bigFontPaint.setStyle(Paint.Style.FILL_AND_STROKE);
//        mTextPaint.setStrokeWidth(DensityUtils.dp2px(context, 1));
        //修正
        bigSize = (int) getScalefontSizePx(max - 1, DensityUtil.sp2px(context, standerSize));
        smallSize =getScalefontSizePx(0.6F, DensityUtil.sp2px(context, standerSize));

        bigFontPaint.setTextSize(bigSize);
        textbigScaleX = bigFontPaint.measureText(maxfontText());
        //文字画笔
        smallFontPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        smallFontPaint.setColor(textColor);
        smallFontPaint.setStyle(Paint.Style.FILL_AND_STROKE);


        smallFontPaint.setTextSize(smallSize);

//        mText1Paint.setTextSize(DensityUtil.sp2px(context, bigSize));
        textsmallScaleX = smallFontPaint.measureText(minFontText());

        //文字画笔
        mText2Paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mText2Paint.setColor(textColor);
        mText2Paint.setStyle(Paint.Style.FILL_AND_STROKE);
        mText2Paint.setTextSize(DensityUtil.sp2px(context, standerSize));
        text2ScaleX = mText2Paint.measureText(getStandFontText());

        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setColor(circleColor);
        mCirclePaint.setStyle(Paint.Style.FILL);

        // 设置阴影效果
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        mCirclePaint.setShadowLayer(2, 0, 0, Color.rgb(33, 33, 33));
    }

    @NonNull
    private String getStandFontText() {
        return getContext().getText(R.string.stand_defaultfont).toString();
    }


    private void initCustomAttr(int attr, TypedArray typedArray) {
        if (attr == R.styleable.FontSizeView_lineColor) {
            lineColor = typedArray.getColor(attr, defaultLineColor);
        } else if (attr == R.styleable.FontSizeView_circleColor) {
            circleColor = typedArray.getColor(attr, defaultCircleColor);
        } else if (attr == R.styleable.FontSizeView_lineWidth) {
            lineWidth = typedArray.getDimensionPixelSize(attr, defaultLineWidth);
        } else if (attr == R.styleable.FontSizeView_circleRadius) {
            circleRadius = typedArray.getDimensionPixelSize(attr, defaultCircleRadius);
        } else if (attr == R.styleable.FontSizeView_totalCount) {
            max = typedArray.getInteger(attr, defaultMax);
        } else if (attr == R.styleable.FontSizeView_textFontColor) {
            textColor = typedArray.getColor(attr, textColor);
        } else if (attr == R.styleable.FontSizeView_smallSize) {
            smallSize = typedArray.getInteger(attr, (int) smallSize);
        } else if (attr == R.styleable.FontSizeView_standerSize) {
            standerSize = typedArray.getInteger(attr, standerSize);
        } else if (attr == R.styleable.FontSizeView_bigSize) {
            bigSize = typedArray.getInteger(attr, bigSize);
        } else if (attr == R.styleable.FontSizeView_defaultPosition) {
            defaultProgress = typedArray.getInteger(attr, (int) defaultProgress);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        height = h;
        width = w;
        circleY = height / 2;
        // 横线宽度是总宽度-2个圆的半径
        itemWidth = (w - 2 * circleRadius) / max;
        // 把可点击点保存起来
        for (int i = 0; i <= max; i++) {
            points.add(new PointF(circleRadius + i * itemWidth, height / 2));
        }
        if (allowFreeProgerss) {
            currentX = progress2Width(width, defaultProgress, max);
        } else {
            //初始刻度
            currentX = points.get((int) defaultProgress).x;

        }
    }


    public static float widthX2Progress(float viewWidth, float currentX, float maxProgress) {


/*        float width=500;
        float current=250;
        float ratio=current/width;// 得到比1小的比例

        float myMaxProgress=15;
        float result=myMaxProgress*ratio;*/

        float ratio = currentX / viewWidth;
        float result = maxProgress * ratio;
        return result;

    }

    public static float progress2Width(float viewWidth, float progress, float maxProgress) {
        float ratio = progress / maxProgress;
        float result = ratio * viewWidth;
        return result;

    }

    boolean hasDraw = false;
    boolean allowFreeProgerss = true;

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);
       // if (!hasDraw) {
            //画字
            canvas.drawText(minFontText(), points.get(0).x - ((textsmallScaleX / 2) + 10) / 2, height / 2 - 50, smallFontPaint);

            //画字
            canvas.drawText(getStandFontText(), points.get((int) standPosition).x - text2ScaleX / 2, height / 2 - 50, mText2Paint);

            //画字
            canvas.drawText(maxfontText(), points.get(points.size() - 1).x - ((textbigScaleX / 2) + 10), height / 2 - 50, bigFontPaint);

            // 先画中间的横线
            canvas.drawLine(points.get(0).x, height / 2, points.get(points.size() - 1).x, height / 2, mLinePaint);


            // 绘制刻度

            for (PointF point : points) {
                canvas.drawLine(point.x + 1, height / 2 - 20, point.x + 1, height / 2 + 20, mLinePaint);
            }
            hasDraw = false;
    //    }


        // 画圆
        if (currentX < circleRadius) {
            currentX = circleRadius;
        }
        if (currentX > width - circleRadius) {
            currentX = width - circleRadius;
        }

        // 实体圆
        canvas.drawCircle(currentX + 1, circleY, circleRadius, mCirclePaint);
    }

    @NonNull
    private String maxfontText() {
        return "b";
    }

    @NonNull
    private static String minFontText() {
        return "A";
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        currentX = event.getX();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                //回到最近的一个刻度点
                PointF targetPoint = getNearestPoint(currentX);
                if (targetPoint != null) {
                    // 最终
                    currentX = targetPoint.x;//points.get(currentProgress).x;
                    invalidate();
                }
                if (onChangeCallbackListener != null) {
                    onChangeCallbackListener.onChangeListener(currentProgress);
                    hasChange = !(currentProgress == defaultProgress);
                }
                break;
        }
        return true;
    }

    /**
     * 获取最近的刻度
     */
    private PointF getNearestPoint(float x) {
        for (int i = 0; i < points.size(); i++) {
            PointF point = points.get(i);
            if (Math.abs(point.x - x) < itemWidth / 2) {
                if (allowFreeProgerss) {
                    currentProgress = widthX2Progress(width, x, max);
                    return new PointF(x, point.y);
                } else {
                    currentProgress = i;
                    return point;

                }
//                return new PointF((int) x, point.y);
            }
        }
        return null;
    }

    public void setChangeCallbackListener(OnChangeCallbackListener listener) {
        this.onChangeCallbackListener = listener;
    }

    private OnChangeCallbackListener onChangeCallbackListener;

    public float getCurrentScaleRatio() {
        return getCurrentScaleRatio(getCurrentProgress());
    }

    public float getCurrentScaleRatio(float currentProgress) {
        if (currentProgress == getStandPosition()) {
            return 1;
        }

        float result = (currentProgress * 1.0f / getStandPosition());//限制最小缩放 0.3但是会导致找不到标准位..
        if (result < 0.2) {
            return 0.2f;
        }
        return result;
    }

    /**
     * @param position          progress
     * @param beforedimensionPx int dimension = getResources().getDimensionPixelSize(R.dimen.sp_stander);
     * @return
     */
    public float getScalefontSizePx(float position, float beforedimensionPx) {
        float fontScaleRatio = getCurrentScaleRatio(position);
        return fontScaleRatio * beforedimensionPx;
//        fontBinding.tvShow.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizeScale * dimension);
    }

    public interface OnChangeCallbackListener {
        void onChangeListener(float position);
    }

    boolean hasChange = false;

    public boolean hasChangge() {
        return hasChange;
    }

    public void setDefaultProgress(float position) {
        if (position > max - 1) {
            Log.e("ERROR_FONT ", "error position: " + position);
            return;
        }
        defaultProgress = position;
        if (onChangeCallbackListener != null) {
            onChangeCallbackListener.onChangeListener(defaultProgress);
        }
        invalidate();
    }
}

相关文章

网友评论

      本文标题:[改造]微信缩放字体view的改造

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