凌雪
2018-10-24
来源 :网络
阅读 1202
评论 0
摘要:本文将带你了解Android应用开发之Android开发之安卓二维码实现方法,希望本文对大家学Android有所帮助。
本文将带你了解Android应用开发之Android开发之安卓二维码实现方法,希望本文对大家学Android有所帮助。
<code><uses-feature android:name="android.hardware.camera"><uses-feature android:name="android.hardware.camera.autofocus"> <uses-permission android:name="android.permission.VIBRATE"><uses-permission android:name="android.permission.WAKE_LOCK"><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"><uses-permission android:name="android.permission.INTERNET"></uses-permission></uses-permission></uses-permission></uses-permission></uses-feature></uses-feature></code>
RelativeLayout
xmlns:android=”https://schemas.android.com/apk/res/android”
xmlns:app=”https://schemas.android.com/apk/res-auto”
xmlns:tools=”https://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”.MainActivity”>
<code><code><linearlayout android:focusable="true" android:focusableintouchmode="true" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"><button android:id="@+id/startScan_bt" android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent" android:text="开始扫描二维码"> <textview android:id="@+id/scanContent_tv" android:layout_height="0dp" android:layout_weight="3" android:layout_width="match_parent" android:scrollbars="vertical"> <edittext android:hint="请输入要生成二维码的内容" android:id="@+id/generateContent_et" android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent"> </edittext></textview></button><button android:id="@+id/generate_bt" android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent" android:text="生成二维码"> <imageview android:id="@+id/twoDimensionalCode_iv" android:layout_height="0dp" android:layout_weight="5" android:layout_width="match_parent"> </imageview></button></linearlayout></code></code>
//工具类
package com.example.mytwoma;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.util.Hashtable;
import java.util.Random;
/**
* date:2016/7/27
* author:易宸锋(dell)
* function:
*/
public class BitmapUtil {
<code><code><code>/** * 根据指定内容生成自定义宽高的二维码图片 * * @param logoBmp logo图标 * @param content 需要生成二维码的内容 * @param QR_WIDTH 二维码宽度 * @param QR_HEIGHT 二维码高度 * @return 二维码的图片 * @throws WriterException 生成二维码异常 */public static Bitmap makeQRImage(Bitmap logoBmp, String content, int QR_WIDTH, int QR_HEIGHT) throws WriterException { try { // 图像数据转换,使用了矩阵转换 Hashtable<encodehinttype, object=""> hints = new Hashtable<encodehinttype, object="">(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 容错率/*hints.put(EncodeHintType.MARGIN, 2); // default is 4hints.put(EncodeHintType.MAX_SIZE, 350);hints.put(EncodeHintType.MIN_SIZE, 100);*/ BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints); int[] pixels = new int[QR_WIDTH * QR_HEIGHT]; for (int y = 0; y < QR_HEIGHT; y++) { // 下面这里按照二维码的算法,逐个生成二维码的图片,//两个for循环是图片横列扫描的结果 for (int x = 0; x < QR_WIDTH; x++) { if (bitMatrix.get(x, y)) { if (x < QR_WIDTH / 2 && y < QR_HEIGHT / 2) { pixels[y * QR_WIDTH + x] = Color.BLUE;// 蓝色 Integer.toHexString(new Random().nextInt()); } else if (x < QR_WIDTH / 2 && y > QR_HEIGHT / 2) { pixels[y * QR_WIDTH + x] = Color.RED;// 红色 } else if (x > QR_WIDTH / 2 && y > QR_HEIGHT / 2) { pixels[y * QR_WIDTH + x] = Color.GREEN;// 绿色 } else { pixels[y * QR_WIDTH + x] = Color.CYAN;// 青色 } } else { pixels[y * QR_WIDTH + x] = 0xffffffff;// 白色 } } } // ------------------添加图片部分------------------// Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888); // 设置像素点 bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT); // 获取图片宽高 int logoWidth = logoBmp.getWidth(); int logoHeight = logoBmp.getHeight(); if (QR_WIDTH == 0 || QR_HEIGHT == 0) { return null; } if (logoWidth == 0 || logoHeight == 0) { return bitmap; } // 图片绘制在二维码中央,合成二维码图片 // logo大小为二维码整体大小的1/5 float scaleFactor = QR_WIDTH * 1.0f / 5 / logoWidth; try { Canvas canvas = new Canvas(bitmap); canvas.drawBitmap(bitmap, 0, 0, null); canvas.scale(scaleFactor, scaleFactor, QR_WIDTH / 2, QR_HEIGHT / 2); canvas.drawBitmap(logoBmp, (QR_WIDTH - logoWidth) / 2, (QR_HEIGHT - logoHeight) / 2, null); canvas.save(Canvas.ALL_SAVE_FLAG); canvas.restore(); return bitmap; } catch (Exception e) { bitmap = null; e.getStackTrace(); } } catch (WriterException e) { e.printStackTrace(); } return null;} /** * 获取十六进制的颜色代码.例如 "#6E36B4" , For HTML , * * @return String 十六进制颜色代码 */public static String getRandColorCode() { String r, g, b; Random random = new Random(); r = Integer.toHexString(random.nextInt(256)).toUpperCase(); g = Integer.toHexString(random.nextInt(256)).toUpperCase(); b = Integer.toHexString(random.nextInt(256)).toUpperCase(); r = r.length() == 1 ? "0" + r : r; g = g.length() == 1 ? "0" + g : g; b = b.length() == 1 ? "0" + b : b; return r + g + b;} /** * 根据指定内容生成自定义宽高的二维码图片 * * @param content 需要生成二维码的内容 * @param width 二维码宽度 * @param height 二维码高度 * @throws WriterException 生成二维码异常 */public static Bitmap makeQRImage(String content, int width, int height) throws WriterException { Hashtable<encodehinttype, string=""> hints = new Hashtable<encodehinttype, string="">(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 图像数据转换,使用了矩阵转换 BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); int[] pixels = new int[width * height]; // 按照二维码的算法,逐个生成二维码的图片,两个for循环是图片横列扫描的结果 for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (bitMatrix.get(x, y)) pixels[y * width + x] = 0xff000000; else pixels[y * width + x] = 0xffffffff; } } // 生成二维码图片的格式,使用ARGB_8888 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap;} /** * 从资源文件中获取图片转化成bitmap类型 * * @param context 上下文 * @param drawableId 资源文件id * @return 转换后的图片 */public static Bitmap gainBitmap(Context context, int drawableId) { Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), drawableId); return bmp;} /** * 在图片右下角添加水印 * * @param srcBMP 原图 * @param markBMP 水印88图片 * @return 合成水印后的图片 */public static Bitmap composeWatermark(Bitmap srcBMP, Bitmap markBMP) { if (srcBMP == null) { return null; } // 创建一个新的和SRC长度宽度一样的位图 Bitmap newb = Bitmap.createBitmap(srcBMP.getWidth(), srcBMP.getHeight(), Bitmap.Config.ARGB_8888); Canvas cv = new Canvas(newb); // 在 0,0坐标开始画入原图 cv.drawBitmap(srcBMP, 0, 0, null); // 在原图的右下角画入水印 cv.drawBitmap(markBMP, srcBMP.getWidth() - markBMP.getWidth() * 4 / 5, srcBMP.getHeight() * 2 / 7, null); // 保存 cv.save(Canvas.ALL_SAVE_FLAG); // 存储 cv.restore(); return newb;} /** * 给二维码图片加背景 * * @param foreground * @param background * @return */public static Bitmap addBackground(Bitmap foreground, Bitmap background) { int bgWidth = background.getWidth(); int bgHeight = background.getHeight(); int fgWidth = foreground.getWidth(); int fgHeight = foreground.getHeight(); Bitmap newmap = Bitmap .createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(newmap); canvas.drawBitmap(background, 0, 0, null); canvas.drawBitmap(foreground, (bgWidth - fgWidth) / 2, (bgHeight - fgHeight) * 3 / 5 + 70, null); canvas.save(Canvas.ALL_SAVE_FLAG); canvas.restore(); return newmap;}</encodehinttype,></encodehinttype,></encodehinttype,></encodehinttype,></code></code></code>
}
//主代码
package com.example.mytwoma;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.WriterException;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//开始扫码(按钮)
private Button startScan_bt;
//扫码结果(文本)
private TextView scanContent_tv;
//输入要生成二维码的内容(输入框)
private EditText generateContent_et;
//开始生成二维码(按钮)
private Button generate_bt;
//显示二维码(显示图片)
private ImageView twoDimensionalCode_iv;
//保存图片(按钮)
private Button saveBitmap_bt;
<code><code><code><code>//生成的二维码放在这个bitmap里面Bitmap bitmap = null; //请求码private final int requestCode = 0; @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化 initView();} /** * 对控件进行初始化. */private void initView() { startScan_bt = (Button) findViewById(R.id.startScan_bt); scanContent_tv = (TextView) findViewById(R.id.scanContent_tv); generateContent_et = (EditText) findViewById(R.id.generateContent_et); generate_bt = (Button) findViewById(R.id.generate_bt); twoDimensionalCode_iv = (ImageView) findViewById(R.id.twoDimensionalCode_iv); //saveBitmap_bt = (Button) findViewById(R.id.saveBitmap__bt); //设置监听事件 startScan_bt.setOnClickListener(this); generate_bt.setOnClickListener(this);} /** * 当两个按钮分别被点击时,做对应的处理. * * @param view */@TargetApi(Build.VERSION_CODES.N)@Overridepublic void onClick(View view) { switch (view.getId()) { //点击扫描时,所做的操作 case R.id.startScan_bt: //弹个吐司. Toast.makeText(MainActivity.this, "开始扫描二维码", Toast.LENGTH_SHORT).show(); //创建一个意图,,指定跳转到CaptureActivity页面,所以对应的要在清单文件里进行配置 Intent intent = new Intent(MainActivity.this, CaptureActivity.class); startActivityForResult(intent,5); break; //点击生成二维码时,所做的操作 case R.id.generate_bt: //得到EditText控件的用户输入信息,并进行非null判断. String content = generateContent_et.getText().toString(); if (null == content || "".equals(content)) { Toast.makeText(MainActivity.this, "输入内容不能为空", Toast.LENGTH_SHORT).show(); } else { //通过EncodingHandler,调用createQRCode,有两个参数,一个字符串信息,一个设置生成图片的宽的值,因为二维码是正方形 try {</code></code></code></code>
// bitmap = EncodingHandler.createQRCode(content, twoDimensionalCode_iv.getWidth());
bitmap = BitmapUtil.makeQRImage(BitmapUtil.gainBitmap(MainActivity.this, R.drawable.e),content, twoDimensionalCode_iv.getWidth(), twoDimensionalCode_iv.getHeight());
} catch (WriterException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, “由于未知原因,生成失败,请稍后重试”, Toast.LENGTH_SHORT).show();
return;
}
//通过方法得到一个Bitmap,然后设置给imageView控件中.
twoDimensionalCode_iv.setImageBitmap(bitmap);
}
break;
<code><code><code><code><code> }} /** * 把毫秒转换时分秒 * * @param millis 毫秒 * @return 转换后的时分秒 */@RequiresApi(api = Build.VERSION_CODES.N)public String getMS_Turn_Date(long millis) { Date date = new Date(millis); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); return sdf.format(date);} /** * onActivityResult:得到CaptureActivity返回的结果进行处理. * * @param requestCode * @param resultCode * @param data */@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) { //对返回的响应码进行判断,== RESULT_OK的话,成功得到结果 if(requestCode == 5 ){ //处理扫描结果(在界面上显示) if (null != data) { Bundle bundle = data.getExtras(); if (bundle == null) { return; } if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) { String result = bundle.getString(CodeUtils.RESULT_STRING); Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show(); } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) { Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show(); } } } super.onActivityResult(requestCode, resultCode, data);}</code></code></code></code></code>
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号