低級錯誤的教訓(xùn)->bitmap轉(zhuǎn)drawable

一,根據(jù)字體內(nèi)容拉伸背景

package com.msyc.onion.utils

import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import com.blankj.utilcode.util.ConvertUtils.dp2px
import com.blankj.utilcode.util.ConvertUtils.sp2px
import com.msyc.onion.R
import java.lang.Math.abs

/**
 * @author: fangyichao
 * @date: 2021/2/3
 */
class BitmapUtil {
    companion object {
        fun setBitmap(context: Context, text: String): Drawable {
            val textPaint = Paint()
            textPaint.style = Paint.Style.FILL
            textPaint.strokeWidth = 8f
            textPaint.textSize = sp2px(15f).toFloat()
            textPaint.textAlign = Paint.Align.CENTER
            //獲取text 大小
            val tBounds = Rect()
            textPaint.getTextBounds(text, 0, text.length, tBounds)

            // 字體padding
            val padding = dp2px(10f)

            val realTextBounds = Rect(0, 0, abs(tBounds.right - tBounds.left),
                    abs(tBounds.top - tBounds.bottom))

            // 整個畫布范圍
            val canvasBounds = Rect(0, 0, realTextBounds.width() + padding * 2, realTextBounds.height() + 2 * padding)

            // 背景
            val bitmap = Bitmap.createBitmap(canvasBounds.width(), canvasBounds.height(), Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)

            //圖片背景paint
            val bgPaint = Paint()
            bgPaint.style = Paint.Style.FILL

            val bitmapBG = BitmapFactory.decodeResource(context.resources, R.drawable.ic_bg_group_price)
                    .copy(Bitmap.Config.ARGB_8888, true)
            val srcBounds = Rect(0, 0, bitmapBG.width, bitmapBG.height)
            canvas.drawBitmap(bitmapBG, srcBounds, canvasBounds, bgPaint)

            //計算baseline
            val fontMetrics = textPaint.fontMetrics
            val distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
            val baseline: Float = canvasBounds.centerY() + distance
            canvas.drawText(text, canvasBounds.centerX().toFloat(), baseline, textPaint)
            return BitmapDrawable(context.resources, bitmap)
        }
    }
}

二,背景大小不變

 /**
     * 文字繪制在圖片上,并返回bitmap對象
     */
    public static Bitmap setTextToImg(Context context, @DrawableRes int drawId, String text) {
        BitmapDrawable icon = (BitmapDrawable) context.getResources().getDrawable(drawId);
//        int width = DensityUtil.sp2px(context, 34);
//        int hight = DensityUtil.sp2px(context, 12);
        //建立一個空的Bitmap
//        Bitmap bitmap = Bitmap.createBitmap(width, hight, Bitmap.Config.ARGB_8888);
        Bitmap bitmap = icon.getBitmap().copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        // 抗鋸齒
        paint.setAntiAlias(true);
        // 防抖動
        paint.setDither(true);
        paint.setTextSize(DensityUtil.sp2px(context, 9));
        paint.setColor(Color.parseColor("#ffffff"));
        canvas.drawText(text, 0, 0, paint);
        return bitmap;
    }

三沟于、layout轉(zhuǎn)drawable

    public static Drawable LayoutToDrawable(Context context, int layout_id, String text) {
        View view = LayoutInflater.from(context).inflate(layout_id, null);
        TextView textView = (TextView) view.findViewById(R.id.content);
        textView.setText(text);
        int size = (int) textView.getText().length();
        Bitmap bitmap = convertViewToBitmap(context, view, size);
//        Drawable drawable = (Drawable) new BitmapDrawable(bitmap);
        BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap);
        return drawable;
    }

    private static Bitmap convertViewToBitmap(Context context, View view, int size) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
//        int width = (int) (size * DeviceUtil.spToPx(12f, context));//根據(jù)字符串的長度顯示view的寬度
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); // 原始大小
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

靈魂咆哮:
一般的轉(zhuǎn)換方式采用如下的方法進行轉(zhuǎn)換:
BitmapDrawable drawable = new BitmapDrawable(bitmap);
但這種方式,轉(zhuǎn)換出來的drawable永遠比bitmap原來的大小不統(tǒng)一(基本上會小于bitmap)

出現(xiàn)此種情況時植康,采用如下方式即可旷太,因為轉(zhuǎn)換中會存在單位換算,需要傳入轉(zhuǎn)換環(huán)境
Resources resources = context.getResources();
BitmapDrawable drawable = new BitmapDrawable(resources, bitmap);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末销睁,一起剝皮案震驚了整個濱河市供璧,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌冻记,老刑警劉巖睡毒,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異冗栗,居然都是意外死亡演顾,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門贞瞒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來偶房,“玉大人,你說我怎么就攤上這事军浆∽匮螅” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵乒融,是天一觀的道長掰盘。 經(jīng)常有香客問我摄悯,道長,這世上最難降的妖魔是什么愧捕? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任奢驯,我火速辦了婚禮,結(jié)果婚禮上次绘,老公的妹妹穿的比我還像新娘瘪阁。我一直安慰自己,他們只是感情好邮偎,可當(dāng)我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布管跺。 她就那樣靜靜地躺著,像睡著了一般禾进。 火紅的嫁衣襯著肌膚如雪豁跑。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天泻云,我揣著相機與錄音艇拍,去河邊找鬼。 笑死宠纯,一個胖子當(dāng)著我的面吹牛卸夕,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播征椒,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼娇哆,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了勃救?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤治力,失蹤者是張志新(化名)和其女友劉穎蒙秒,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體宵统,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡晕讲,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了马澈。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瓢省。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖痊班,靈堂內(nèi)的尸體忽然破棺而出勤婚,到底是詐尸還是另有隱情,我是刑警寧澤涤伐,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布馒胆,位于F島的核電站缨称,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏祝迂。R本人自食惡果不足惜睦尽,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望型雳。 院中可真熱鬧当凡,春花似錦、人聲如沸纠俭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽柑晒。三九已至欧瘪,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間匙赞,已是汗流浹背佛掖。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留涌庭,地道東北人芥被。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像坐榆,于是被迫代替她去往敵國和親拴魄。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容