|
- 文本转成图片2 s6 d/ w* W& k- ?+ e8 `- u" E
- # c# p7 u, v3 l) K0 ]
- /**: q K) F/ B8 z
- * 核心,文本转成图片5 H+ c, Z$ t& w
- * @param bitmap 原图片
; R2 X! R. c: A4 c) r& j - * @param text 文本
; b- }# @! D ] - * @param fontSize 文字大小
! R4 @' ~1 f f) O - * @return+ q; F7 [+ U9 w) _
- */
/ d5 C( v$ b1 i( m# N - public static Bitmap getTextBitmap(Bitmap bitmap,int backColor, String text, int fontSize)
" i1 Y9 ^5 ^) |0 U9 Y - { b* W. e* z* N4 n" K; w
- if(bitmap==null)7 d9 Y7 H9 ?0 G( |( H/ E& q
- throw new IllegalArgumentException("Bitmap cannot be null.");
, j2 v3 M& Z0 Q& X X5 S - int picWidth=bitmap.getWidth();0 M; h5 R2 L3 S P. u' V: n9 B
- int picHeight=bitmap.getHeight();
' @0 [) Q7 V4 I. o4 j, _, } - Bitmap back= Bitmap.createBitmap((bitmap.getWidth()%fontSize==0)?bitmap.getWidth():((bitmap.getWidth()/fontSize)*fontSize)
) E2 h% Z8 G: \ - ,(bitmap.getHeight()%fontSize==0)?bitmap.getHeight():((bitmap.getHeight()/fontSize)*fontSize)
# v' H- L: v' A# C3 H: c7 O - , Bitmap.Config.ARGB_8888);) H" B8 w$ k ]( H! u* Q# s
- Canvas canvas=new Canvas(back);9 ?- B- x7 |5 P) A# h
- canvas.drawColor(backColor);7 G* C5 W8 g0 q9 y# F$ u
- int idx=0;
% O* D7 ]4 C" @8 S9 ^ - for(int y=0;y<picHeight;y+=fontSize)1 K/ ], P8 m4 T% X5 p+ c0 J* e
- {$ l5 I: e' `. \" d( z- q5 m0 W
- for(int x=0;x<picWidth;x+=fontSize)1 S1 i$ L. C& ^& D# p" @( ?$ F. Y
- {
/ P. q; [! I! |( i) q - int[] colors=getPixels(bitmap,x,y,fontSize,fontSize );
5 @1 S: r5 j; r: |
+ F J1 @* Z0 X& x3 I- Paint paint=new Paint();/ m, v" D" n, Z$ `
- paint.setAntiAlias(true);3 }6 d, `( t+ D+ f6 g+ ^2 g8 h% [
- paint.setColor(getAverage(colors));( k" Q5 f$ N+ f( W+ a
- paint.setTextSize(fontSize);
`( i i7 |0 c" J/ A+ V - Paint.FontMetrics fontMetrics =paint.getFontMetrics();' c/ k/ y8 g6 u: `# X! z5 a
- float padding=(y==0)?(fontSize+fontMetrics.ascent):((fontSize+fontMetrics.ascent)*2);0 u' E( G$ |5 `) A3 d
- canvas.drawText(String.valueOf(text.charAt(idx++)),x,y-padding,paint);
+ z# g0 R/ a q+ u! Y7 T - if(idx==text.length())
; t2 a1 Z8 i$ Q2 C/ M: B3 W9 v' q% p - {
0 [% F \0 |- \, Q0 A9 ~# r5 F - idx=0;1 x2 n. r$ S5 o# T ?+ A
- }( v3 c6 H" P% A; W
r1 P0 D5 }* w% T6 M- }, V, g5 a6 F5 Z$ b' y- m, K% [9 {
- }
: [2 v" E9 ^2 Z. c. g - ! _- F* ^; e7 {$ L# ~, y
- return back;" q4 h( \% ^' b a9 s
- }
' A. T) Z; O4 p
复制代码 |
|