直播商城系统源码,安卓验证码的简单实现
直播商城系统源码,安卓验证码的简单实现
首先是要获取 随机的四个字母组合,我这里是将26个字母存储到一个数组中,然后随机生成4个下标值,取这四个下标值对应的字母作为验证码。
public class RandomChars {
char[] chars;
public RandomChars() {
chars = new char[26];
for (int i = 0; i < 26; i++) {
chars[i] = (char) (i + 65);
}
}
public char[] get4Chars() {
char[] rlt = new char[4];
for (int i = 0; i < rlt.length; i++) {
int randomIndex = (int) (Math.random() * 26);
rlt[i] = chars[randomIndex];
}
return rlt;
}
}
自定义一个CodeView进行验证码的绘制,主要在onDraw方法中操作,学艺不精,还不能好好在onMeasure中控制大小位置等。
float unitWidth = (float) getWidth() / (float) chars.length;
for (int i = 0; i < chars.length; i++) {
String str = chars[i] + "";
textPaint.getTextBounds(str, 0, str.length(), mRect);
resetColor();
int angel = (int) (Math.random()*(8-(-8)+1)+(-8));
canvas.rotate(angel);//旋转字母,随机角度
canvas.drawText(str, i * unitWidth + 5, getHeight() / 2 - mRect.centerY(), textPaint);
/**
* 很关键,旋转
*/
canvas.save();//保存状态
canvas.restore();//恢复
}
/**
* 重新设置随机颜色
*/
private void resetColor() {
int r = (int) (Math.random() * 230 - 30);
int g = (int) (Math.random() * 230 - 30);
int b = (int) (Math.random() * 230 - 30);
textPaint.setColor(Color.rgb(r, g, b));
}
以上就是 直播商城系统源码,安卓验证码的简单实现,更多内容欢迎关注之后的文章