转载请注明出处:王亟亟的大牛之路
上一篇博文写了一个生成二维码的,这一篇来一个随机数的。
包目录
运行效果:
就是画了一串东西然后放入imageview
话不多说直接上代码:
public class MainActivity extends Activity {
ProgressDialog mLoadingDialog;
Button ShowCAPTCHAD;
ImageView imageview;
Bitmap validateCodeImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview=(ImageView)findViewById(R.id.imageview);
ShowCAPTCHAD=(Button)findViewById(R.id.ShowCAPTCHAD);
ShowCAPTCHAD.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showLoadingDialog("Loading......");
//回收bitmap
if(null != validateCodeImage && !validateCodeImage.isRecycled()){
validateCodeImage.recycle();
validateCodeImage = null;
}
//生成图片
validateCodeImage =makeValidateCode(200, 70);
imageview.setImageBitmap(validateCodeImage);
Toast.makeText(MainActivity.this, "验证码生成成功"+"验证码是"+gainValidateCodeValue(), Toast.LENGTH_SHORT).show();
dismissLoadingDialog();
}
});
}
/*显示对话框*/
public void showLoadingDialog(String msg) {
if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
return;
}
mLoadingDialog = new ProgressDialog(this);
mLoadingDialog.setMessage(msg);
// mLoadingDialog.setOnKeyListener(mOnKeyListener);
// mLoadingDialog.setCancelable(false);
mLoadingDialog.show();
}
/**
* 取消加载对话框
*/
public void dismissLoadingDialog() {
if (mLoadingDialog != null) {
mLoadingDialog.dismiss();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 获取验证码图片
* @param width 验证码宽度
* @param height 验证码高度
* @return 验证码Bitmap对象
*/
public synchronized static Bitmap makeValidateCode(int width, int height){
return ValidateCodeGenerator.createBitmap(width, height);
}
/**
* 获取验证码值
* @return 验证码字符串
*/
public synchronized static String gainValidateCodeValue(){
return ValidateCodeGenerator.getCode();
}
/**
* 随机生成验证码内部类
*
*/
final static class ValidateCodeGenerator{
private static final char[] CHARS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
};
//default settings
private static final int DEFAULT_CODE_LENGTH = 4;
private static final int DEFAULT_FONT_SIZE = 30;
private static final int DEFAULT_LINE_NUMBER =3;//杂乱线的条数
private static final int BASE_PADDING_LEFT = 15, RANGE_PADDING_LEFT = 10, BASE_PADDING_TOP = 35, RANGE_PADDING_TOP = 20;
private static final int DEFAULT_WIDTH = 60, DEFAULT_HEIGHT = 30;
//variables
private static String value;
private static int padding_left, padding_top;
private static Random random = new Random();
public static Bitmap createBitmap(int width,int height) {
padding_left = 0;
//创建画布
Bitmap bp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas c = new Canvas(bp);
//随机生成验证码字符
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < DEFAULT_CODE_LENGTH; i++) {
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
value = buffer.toString();
//设置颜色
c.drawColor(Color.WHITE);
//设置画笔大小
Paint paint = new Paint();
paint.setTextSize(DEFAULT_FONT_SIZE);
for (int i = 0; i < value.length(); i++) {
//随机样式
randomTextStyle(paint);
padding_left += BASE_PADDING_LEFT + random.nextInt(RANGE_PADDING_LEFT);
padding_top = BASE_PADDING_TOP + random.nextInt(RANGE_PADDING_TOP);
c.drawText(value.charAt(i) + "", padding_left, padding_top, paint);
}
for (int i = 0; i < DEFAULT_LINE_NUMBER; i++) {
drawLine(c, paint);
}
//保存
c.save(Canvas.ALL_SAVE_FLAG);
c.restore();
return bp;
}
public static String getCode() {
return value;
}
private static void randomTextStyle(Paint paint) {
int color = randomColor(1);
paint.setColor(color);
paint.setFakeBoldText(random.nextBoolean());//true为粗体,false为非粗体
float skewX = random.nextInt(11) / 10;
skewX = random.nextBoolean() ? skewX : -skewX;
paint.setTextSkewX(skewX); //float类型参数,负数表示右斜,整数左斜
paint.setUnderlineText(true); //true为下划线,false为非下划线
paint.setStrikeThruText(true); //true为删除线,false为非删除线
}
private static void drawLine(Canvas canvas, Paint paint) {
int color = randomColor(1);
int startX = random.nextInt(DEFAULT_WIDTH);
int startY = random.nextInt(DEFAULT_HEIGHT);
int stopX = random.nextInt(DEFAULT_WIDTH);
int stopY = random.nextInt(DEFAULT_HEIGHT);
paint.setStrokeWidth(1);
paint.setColor(color);
canvas.drawLine(startX, startY, stopX, stopY, paint);
}
private static int randomColor(int rate) {
int red = random.nextInt(256) / rate;
int green = random.nextInt(256) / rate;
int blue = random.nextInt(256) / rate;
return Color.rgb(red, green, blue);
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(null != validateCodeImage && !validateCodeImage.isRecycled()){
validateCodeImage.recycle();
validateCodeImage = null;
}
System.gc();
}
}
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.captchademo.MainActivity" >
<Button
android:id="@+id/ShowCAPTCHAD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="ShowCAPTCHAD" />
<ImageView
android:id="@+id/imageview"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/ShowCAPTCHAD"
android:layout_centerHorizontal="true"
android:minHeight="150dp" />
</RelativeLayout>
想要修改属性都可以在内部类操作。
源码地址:http://yunpan.cn/cd8R7TMTtWDwq 访问密码 8a95