自定义TextView实现效果图字体适配

这个是我以前发在EOE上的一个帖子,发现阅读量平平还是发到这里来装饰下我的博客吧。

废话不多说,首先先来说下TextView设置字体这个事情。系统默认的设置字体的方法是sp。先看下全称:sp: scaled pixels.scale顾名思义放缩比例,也就是说系统的sp其实是乘以一个固定的放缩比例设置的,那么我们是不是也做同样的设置呢。

有一个东西我们肯定要清楚,无论我们设置sp,dp其实到最后绘制的时候都是转化成px来使用的。所以我们可以回到一个原点,就是我们通过自己的效果图的大小去自己生成这么一个scale,去执行这个换算步骤。

public class MyTextView extends TextView {

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        TypedArray type = context.obtainStyledAttributes(attrs,
                R.styleable.MyTextView);
        int i = type.getInteger(R.styleable.MyTextView_textSizePx, 25);
        setTextSize(TypedValue.COMPLEX_UNIT_PX, getFontSize(i));
    }
    //  获取当前手机屏幕分辨率 之后根据设计图分辨率高度去换算实际字体大小
    private int getFontSize(int textSize) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        int screenHeight = dm.heightPixels;
        // screenWidth = screenWidth > screenHeight ? screenWidth :
        // screenHeight;
        int rate = (int) (textSize * (float) screenHeight / 1280);
        return rate;
    }
}

好了,同学们,从上面这段代码我们可以通过获取屏幕分辨率的方式去自己换算出我们的scale,之后我们只要去从我们的效果图中把这个字的高度是多少测量出来设置在这个自定义textview中就可以去实现textview的适配问题了。

下面我会把一些res文件里面的关键部分补全给大家看。

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="MyTextView">
        <!-- 自定义属性,format属性表示该属性的单位 -->
        <attr name="textSizePx" format="integer" />
    </declare-styleable>

</resources>
    <com.example.mytextviewdemo.MyTextView
        xmlns:custom="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        app:textSizePx="30" />
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值