由于项目用到要根据4位长度的字符串,生成一个验证码图片,效果如图:
实现代码:
1 /** 2 * 生成验证码图片 3 * 4 * @param width 5 * @param height 6 * @param size 7 * 字体大小(以sp为单位计算) 8 * @param scale 9 * 缩放系数(DisplayMetrics类中属性scaledDensity) 10 * @param securityCode 11 * @return 12 */ 13 public Bitmap createSecurityCodeBitmap(int width, int height, int size, 14 float scale, String securityCode) { 15 16 int textSize = DisplayUtil.sp2px(size, scale); 17 18 Bitmap codeBitmap = Bitmap.createBitmap(width, height, 19 Bitmap.Config.ARGB_8888); 20 Canvas canvas = new Canvas(codeBitmap); 21 canvas.drawColor(getResources().getColor(R.color.color_security_code)); 22 23 TextPaint textPaint = new TextPaint(); 24 25 textPaint.setAntiAlias(true); 26 textPaint.setTextSize(textSize); 27 textPaint.setStrokeWidth(3); 28 textPaint.setStyle(Paint.Style.STROKE); 29 textPaint.setTextAlign(Paint.Align.CENTER); 30 31 int x = (width - textSize * 3) / 2; 32 int y = (height + textSize) / 2; 33 for (int index = 0; index < securityCode.length(); index++) { 34 textPaint.setColor(randomColor(1)); 35 canvas.drawText(securityCode.charAt(index) + "", (x + textSize 36 * index), y, textPaint); 37 } 38 Random random = new Random(); 39 for (int i = 0; i < 5; i++) { 40 textPaint.setStrokeWidth(2); 41 textPaint.setColor(randomColor(1)); 42 canvas.drawLine(random.nextInt(width), random.nextInt(height), 43 random.nextInt(width), random.nextInt(height), textPaint); 44 } 45 canvas.save(Canvas.ALL_SAVE_FLAG); 46 canvas.restore(); 47 return codeBitmap; 48 }
随机设置颜色:
1 private int randomColor(int rate) { 2 Random random = new Random(); 3 int red = random.nextInt(256) / rate; 4 int green = random.nextInt(256) / rate; 5 int blue = random.nextInt(256) / rate; 6 return Color.rgb(red, green, blue); 7 }
用到工具类(来源里网络):
1 public class DisplayUtil { 2 /** 3 * 将px值转换为dip或dp值,保证尺寸大小不变 4 * 5 * @param pxValue 6 * @param scale 7 * (DisplayMetrics类中属性density) 8 * @return 9 */ 10 public static int px2dip(float pxValue, float scale) { 11 return (int) (pxValue / scale + 0.5f); 12 } 13 14 /** 15 * 将dip或dp值转换为px值,保证尺寸大小不变 16 * 17 * @param dipValue 18 * @param scale 19 * (DisplayMetrics类中属性density) 20 * @return 21 */ 22 public static int dip2px(float dipValue, float scale) { 23 return (int) (dipValue * scale + 0.5f); 24 } 25 26 /** 27 * 将px值转换为sp值,保证文字大小不变 28 * 29 * @param pxValue 30 * @param fontScale 31 * (DisplayMetrics类中属性scaledDensity) 32 * @return 33 */ 34 public static int px2sp(float pxValue, float fontScale) { 35 return (int) (pxValue / fontScale + 0.5f); 36 } 37 38 /** 39 * 将sp值转换为px值,保证文字大小不变 40 * 41 * @param spValue 42 * @param fontScale 43 * (DisplayMetrics类中属性scaledDensity) 44 * @return 45 */ 46 public static int sp2px(float spValue, float fontScale) { 47 return (int) (spValue * fontScale + 0.5f); 48 } 49 }