TypedValue.applyDimension的使用

本文详细介绍了Android中TypedValue.applyDimension方法的使用方法及其源码实现。该方法主要用于将不同单位(如dp、sp等)转换为像素单位(px),适用于Android开发过程中尺寸单位的灵活转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TypedValue.applyDimension是一个将各种单位的值转换为像素的方法

用法TypedValue.applyDimension(int unit, float value,DisplayMetrics metrics) 

 

源码分析:

public static float applyDimension(int unit, float value,  
                                       DisplayMetrics metrics)  
    {  
        switch (unit) {  
        case COMPLEX_UNIT_PX:  
            return value;  
        case COMPLEX_UNIT_DIP:  
            return value * metrics.density;  
        case COMPLEX_UNIT_SP:  
            return value * metrics.scaledDensity;  
        case COMPLEX_UNIT_PT:  
            return value * metrics.xdpi * (1.0f/72);  
        case COMPLEX_UNIT_IN:  
            return value * metrics.xdpi;  
        case COMPLEX_UNIT_MM:  
            return value * metrics.xdpi * (1.0f/25.4f);  
        }  
        return 0;  
    }

 

使用:

//其他sp,dp转px
    public int value2px(int typeValue,int dpVal)
    {
        return (int) TypedValue.applyDimension(typeValue, dpVal, getResources().getDisplayMetrics());
    }

  

 

转载于:https://www.cnblogs.com/wangjiaghe/p/7611012.html

class AutoResizeTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = android.R.attr.textViewStyle ) : AppCompatTextView(context, attrs, defStyle) { private val availableSpaceRect = RectF() private val sizeTester: SizeTester private var maxTextSize: Float = 0.toFloat() private var spacingMult = 1.0f private var spacingAdd = 0.0f private var minTextSize: Float = 0.toFloat() private var widthLimit: Int = 0 private var maxLines: Int = NO_LINE_LIMIT private var initialized = false private var textPaint: TextPaint private interface SizeTester { /** * @param suggestedSize Size of text to be tested * @param availableSpace available space in which text must fit * @return an integer < 0 if after applying `suggestedSize` to * text, it takes less space than `availableSpace`, > 0 * otherwise */ fun onTestSize(suggestedSize: Int, availableSpace: RectF): Int } init { // using the minimal recommended font size minTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12f, resources.displayMetrics) maxTextSize = textSize textPaint = TextPaint(paint) // prepare size tester: sizeTester = object : SizeTester { val textRect = RectF() override fun onTestSize(suggestedSize: Int, availableSpace: RectF): Int { textPaint.textSize = suggestedSize.toFloat() val transformationMethod = transformationMethod val text: String = transformationMethod?.getTransformation(text, this@AutoResizeTextView) ?.toString() ?: text.toString() val singleLine = maxLines == 1 if (singleLine) { textRect.bottom = textPaint.fontSpacing textRect.right = textPaint.measureText(text) } else { val layout: StaticLayout = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { StaticLayout.Builder.obtain(text, 0, text.length, textPaint, widthLimit) .setLineSpacing(spacingAdd, spacingMult) .setAlignment(Alignment.ALIGN_NORMAL).setIncludePad(true).build() } else { @Suppress("DEPRECATION") StaticLayout( text, textPaint, widthLimit, Alignment.ALIGN_NORMAL, spacingMult, spacingAdd, true ) } // return early if we have more lines if (maxLines != NO_LINE_LIMIT && layout.lineCount > maxLines) return 1 textRect.bottom = layout.height.toFloat() var maxWidth = -1 val lineCount = layout.lineCount for (i in 0 until lineCount) { val end = layout.getLineEnd(i) if (i < lineCount - 1 && end > 0 && !isValidWordWrap(text[end - 1])) return 1 if (maxWidth < layout.getLineRight(i) - layout.getLineLeft(i)) maxWidth = layout.getLineRight(i).toInt() - layout.getLineLeft(i).toInt() } //for (int i = 0; i < layout.getLineCount(); i++) // if (maxWidth < layout.getLineRight(i) - layout.getLineLeft(i)) // maxWidth = (int) layout.getLineRight(i) - (int) layout.getLineLeft(i); textRect.right = maxWidth.toFloat() } textRect.offsetTo(0f, 0f) return if (availableSpace.contains(textRect)) -1 else 1 // else, too big } } initialized = true } fun isValidWordWrap(c: Char): Boolean { return c == ' ' || c == '-' } override fun setAllCaps(allCaps: Boolean) { super.setAllCaps(allCaps) adjustTextSize() } override fun setTypeface(tf: Typeface?) { super.setTypeface(tf) adjustTextSize() } override fun setTextSize(size: Float) { maxTextSize = size adjustTextSize() } override fun setMaxLines(maxLines: Int) { super.setMaxLines(maxLines) this.maxLines = maxLines adjustTextSize() } override fun getMaxLines(): Int { return maxLines } override fun setSingleLine() { super.setSingleLine() maxLines = 1 adjustTextSize() } override fun setSingleLine(singleLine: Boolean) { super.setSingleLine(singleLine) maxLines = if (singleLine) 1 else NO_LINE_LIMIT adjustTextSize() } override fun setLines(lines: Int) { super.setLines(lines) maxLines = lines adjustTextSize() } override fun setTextSize(unit: Int, size: Float) { val c = context val r: Resources = if (c == null) Resources.getSystem() else c.resources maxTextSize = TypedValue.applyDimension(unit, size, r.displayMetrics) adjustTextSize() } override fun setLineSpacing(add: Float, mult: Float) { super.setLineSpacing(add, mult) spacingMult = mult spacingAdd = add } /** * Set the lower text size limit and invalidate the view, sp value. */ @Suppress("unused") fun setMinTextSize(minTextSize: Float) { this.minTextSize = sp2px(minTextSize).toFloat() adjustTextSize() } private fun adjustTextSize() { // This is a workaround for truncated text issue on ListView, as shown here: https://github.com/AndroidDeveloperLB/AutoFitTextView/pull/14 // TODO think of a nicer, elegant solution. // post(new Runnable() // { // @Override // public void run() // { if (!initialized) return val startSize = minTextSize.toInt() val heightLimit = measuredHeight - compoundPaddingBottom - compoundPaddingTop widthLimit = measuredWidth - compoundPaddingLeft - compoundPaddingRight if (widthLimit <= 0) return textPaint = TextPaint(paint) availableSpaceRect.right = widthLimit.toFloat() availableSpaceRect.bottom = heightLimit.toFloat() superSetTextSize(startSize) // } // }); } private fun superSetTextSize(startSize: Int) { val textSize = binarySearch(startSize, maxTextSize.toInt(), sizeTester, availableSpaceRect) super.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize.toFloat()) } private fun binarySearch( start: Int, end: Int, sizeTester: SizeTester, availableSpace: RectF ): Int { var lastBest = start var lo = start var hi = end - 1 var mid: Int while (lo <= hi) { mid = (lo + hi).ushr(1) val midValCmp = sizeTester.onTestSize(mid, availableSpace) if (midValCmp < 0) { lastBest = lo lo = mid + 1 } else if (midValCmp > 0) { hi = mid - 1 lastBest = hi } else return mid } // make sure to return last best // this is what should always be returned return lastBest } override fun onTextChanged(text: CharSequence, start: Int, before: Int, after: Int) { super.onTextChanged(text, start, before, after) adjustTextSize() } override fun onSizeChanged(width: Int, height: Int, oldwidth: Int, oldheight: Int) { super.onSizeChanged(width, height, oldwidth, oldheight) if (width != oldwidth || height != oldheight) adjustTextSize() } companion object { private const val NO_LINE_LIMIT = -1 } } 功能描述,并且增加完整注释
最新发布
07-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值