日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

android實現在圖標上顯示數字_Android

作者:球球_2014 ? 更新時間: 2022-06-18 編程語言

本文實例為大家分享了android實現在圖標上顯示數字的具體代碼,供大家參考,具體內容如下

效果圖:

動態顯示當天的號數。

主要代碼如下:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
?
/**
?* 圖片上畫文字
?*?
?* @author qhg
?* @date 2014年3月5日
?*?
?*/
?
public class QNotifacationIcon {
?? ?/**
?? ? * 在給定的圖片上添加文字
?? ? *?
?? ? * @param context
?? ? * ? ? ? ? ? ?上下文對象
?? ? * @param resId
?? ? * ? ? ? ? ? ?圖片資源ID
?? ? * @param text
?? ? * ? ? ? ? ? ?需要顯示的文字
?? ? * @param textSize
?? ? * ? ? ? ? ? ?文字大小
?? ? * @param color
?? ? * ? ? ? ? ? ?文字顏色
?? ? * @param typeface
?? ? * ? ? ? ? ? ?文字字體
?? ? * @param offsetX
?? ? * ? ? ? ? ? ?文字x的偏移量
?? ? * @param offsetY
?? ? * ? ? ? ? ? ?文字y的偏移量
?? ? * @return 帶文字的圖片
?? ? */
?? ?public static Bitmap generatorContactIcon(Context context, int resId,
?? ??? ??? ?String text, float textSize, int color, Typeface typeface,
?? ??? ??? ?float offsetX, float offsetY) {
?? ??? ?// 根據id獲取需要處理的圖片
?? ??? ?Bitmap icon = ((BitmapDrawable) (context.getResources()
?? ??? ??? ??? ?.getDrawable(resId))).getBitmap();
?? ??? ?int iconWidth = icon.getWidth();
?? ??? ?int iconHeight = icon.getHeight();
?? ??? ?// 初始化畫布
?? ??? ?Bitmap contactIcon = Bitmap.createBitmap(iconWidth, iconHeight,
?? ??? ??? ??? ?Config.ARGB_8888);
?? ??? ?// 構建
?? ??? ?Canvas canvas = new Canvas(contactIcon);
?
?? ??? ?// 創建畫筆
?? ??? ?Paint paint = new Paint();
?? ??? ?// 設定是否使用圖像抖動處理,會使繪制出來的圖片顏色更加平滑和飽滿,圖像更加清晰
?? ??? ?paint.setDither(true);
?? ??? ?// 如果該項設置為true,則圖像在動畫進行中會濾掉對Bitmap圖像的優化操作,加快顯示
?? ??? ?// 速度,本設置項依賴于dither和xfermode的設置
?? ??? ?paint.setFilterBitmap(true);
?
?? ??? ?// 截取整個圖片,從左上角到右下角
?? ??? ?Rect src = new Rect(0, 0, iconWidth, iconHeight);
?? ??? ?// 截取的圖片放在畫布上的位置
?? ??? ?Rect dst = new Rect(0, 0, iconWidth, iconHeight);
?? ??? ?canvas.drawBitmap(icon, src, dst, paint);
?
?? ??? ?// 抗鋸齒和使用本身的文本字距
?? ??? ?Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG
?? ??? ??? ??? ?| Paint.DEV_KERN_TEXT_FLAG);
?? ??? ?// 設置文字顏色
?? ??? ?numPaint.setColor(color);
?? ??? ?// 設置文字大小
?? ??? ?numPaint.setTextSize(textSize);
?? ??? ?// 設置文字字體
?? ??? ?numPaint.setTypeface(typeface);
?
?? ??? ?// 將文字內容畫在圖片上,x和y的坐標這里直接計算了文字在圖片上的寬高偏移比例
?? ??? ?canvas.drawText(text, iconWidth * offsetX, iconHeight * offsetY,
?? ??? ??? ??? ?numPaint);
?? ??? ?return contactIcon;
?? ?}
}

數字字體大小會隨屏幕大小而不適應,可以根據屏幕寬度然后動態縮放字體比例。
調用方式:

// 動態在圖片上畫日期數字
((ImageView) convertView.findViewById(R.id.iv_leftImage))
?? ?.setImageBitmap(QNotifacationIcon.generatorContactIcon(
?? ?context, list_left_iamge_array[position],
?? ?String.valueOf(new Date().getDate()), 30f, Color.GRAY,
?? ?Typeface.DEFAULT_BOLD, 0.35f, 0.75f));

原文鏈接:https://blog.csdn.net/qhg2014/article/details/20628605

欄目分類
最近更新