新建项目
布局截图如下(一个输入框,一个按钮,一个imageview),输入想要的东西(文字,数字,网站链接等)然后点击按钮生成二维码,然后可以扫描识别。
首先需要一个谷歌的一个jar包
activity的代码
private EditText et1;
private Button btn1;
private ImageView iv1; private static final int IMAGE_HALFWIDTH = 35;//图片宽度值大小
找到输入框,和按钮,imageview
et1 = (EditText)findViewById(R.id.editText1);
btn1 = (Button)findViewById(R.id.button1);
iv1 = (ImageView)findViewById(R.id.imageView1);
按钮点击事件
btn1.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
String toMakePic_string = et1.getText().toString().trim();
Bitmap logo= BitmapFactory.decodeResource(getResources(),R.drawable._netcfg); try {
Bitmap bm=createCode(toMakePic_string,logo,BarcodeFormat.QR_CODE); //一个方法在下面
iv1.setImageBitmap(bm);
} catch (WriterException e) {
e.printStackTrace();
}
}
});
createCode方法 返回bitmap
public Bitmap createCode(String string,Bitmap mBitmap, BarcodeFormat format)throws WriterException {
//Matrix,中文里叫矩阵,在图像处理方面,主要是用于平面的缩放、平移、旋转等操作。
Matrix m = new Matrix();
float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();
float sy = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getHeight();
m.setScale(sx, sy);//设置缩放信息
//将logo图片按martix设置的信息缩放
mBitmap = Bitmap.createBitmap(mBitmap, 0, 0,mBitmap.getWidth(), mBitmap.getHeight(), m, false);
MultiFormatWriter writer = new MultiFormatWriter();
Hashtable hst = new Hashtable();
hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");//设置字符编码
//生成二维码矩阵信息
BitMatrix matrix = writer.encode(string, format, 800, 800, hst);
int width = matrix.getWidth();//矩阵高度
int height = matrix.getHeight();//矩阵宽度
int halfW = width / 2;
int halfH = height / 2;
int[] pixels = new int[width * height];//定义数组长度为矩阵高度*矩阵宽度,用于记录矩阵中像素信息
for (int y = 0; y < height; y++) {//从行开始迭代矩阵
for (int x = 0; x < width; x++) {//迭代列
if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH && y > halfH - IMAGE_HALFWIDTH && y < halfH + IMAGE_HALFWIDTH) {
//该位置用于存放图片信息
//记录图片每个像素信息
pixels[y * width + x] = mBitmap.getPixel(x - halfW+ IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
}
else {
if (matrix.get(x, y)) {
//如果有黑块点,记录信息
pixels[y * width + x] = 0xff000000;//记录黑块信息
}
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);
// 通过像素数组生成bitmap
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
完成截图(写什么都可以)【】