안 드 로 이 드 는 구 글 Zxing 을 바탕 으로 QR 코드,바코드 스 캔 을 실현 하고 위 챗 QR 코드 스 캔 효 과 를 모방 합 니 다(추천)
위 챗 이 도착 하면 서 QR 코드 가 점점 뜨 거 워 지고 곳곳에서 QR 코드 를 볼 수 있 습 니 다.예 를 들 어 쇼핑 몰,KFC,식당 등 이 있 습 니 다.QR 코드 스 캔 에 대해 저 희 는 구 글 의 오픈 소스 프레임 워 크 Zxing 을 사 용 했 습 니 다.저 희 는 소스 코드 와 Jar 가방 을 다운로드 할 수 있 습 니 다.예전 에 제 항목 의 QR 코드 스 캔 기능 은 스 캔 기능 만 실 현 했 습 니 다.그 UI 는 정말 못 생 겼 습 니 다.좋 은 애플 리 케 이 션 은 그 UI 인터페이스 도 대중 에 게 받 아들 여야 한다.그렇지 않 으 면 사람들 이 너의 소프트웨어 를 사용 하지 않 을 것 이다.그래서 애플 리 케 이 션 기능 과 인터페이스 가 모두 중요 하 다.예 를 들 어 위 챗,위 챗 UI 가 많은 애플 리 케 이 션 에 의 해 모방 되 었 다 고 믿는다.나 도 위 챗 스 캔 2 차원 코드 효 과 를 모방 하여 모방 했다.위 챗 이 그렇게 정교 하 게 만 들 지 는 않 았 지만 효 과 는 괜 찮 았 다.그래서 자신 이 수정 한 UI 코드 와 QR 코드 를 스 캔 한 코드 를 여러분 에 게 공유 합 니 다.첫째,자신 이 프로젝트 에서 똑 같은 기능 을 만 나 직접 복사 해서 사용 하 는 것 입 니 다.둘째,QR 코드 기능 을 추가 하지 않 은 사람 에 게 참고 하 는 것 입 니 다.거인 의 어깨 위 에 서 있 습 니 다.하하,저도 거인 의 어깨 위 에 서서 이 기능 을 추 가 했 습 니 다.그 다음 에 저 를 따라 이 기능 을 실현 하 겠 습 니 다.안 에는 불필요 한 파일 들 이 많이 제거 되 어 있 습 니 다.
우 리 는 먼저 프로젝트 의 구 조 를 살 펴 보 자.
/**
*
* @param result
* @param barcode
*/
public void handleDecode(Result result, Bitmap barcode) {
inactivityTimer.onActivity();
playBeepSoundAndVibrate();
String resultString = result.getText();
if (resultString.equals("")) {
Toast.makeText(MipcaActivityCapture.this, "Scan failed!", Toast.LENGTH_SHORT).show();
}else {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("result", resultString);
bundle.putParcelable("bitmap", barcode);
resultIntent.putExtras(bundle);
this.setResult(RESULT_OK, resultIntent);
}
MipcaActivityCapture.this.finish();
}
4.567917.저 는 Mipca Activity Capture 인터페이스의 구조 에 대해 자신의 변경 을 했 습 니 다.먼저 효과 도 를 살 펴 보 겠 습 니 다.주로 FrameLayout 를 사 용 했 습 니 다.안에 RelativeLayout 가 내장 되 어 있 고 안의 그림 도 위 챗 에서 꺼 냈 습 니 다.평소에 저 는 필요 한 그림 을 보면 위 챗 에서 찾 았 습 니 다.미 공 이 없 는 회사 의 프로그래머 는 핍박 을 받 았 습 니 다 레이아웃 코드 는 다음 과 같 습 니 다.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<SurfaceView
android:id="@+id/preview_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center" />
<com.mining.app.zxing.view.ViewfinderView
android:id="@+id/viewfinder_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<include
android:id="@+id/include1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
layout="@layout/activity_title" />
</RelativeLayout>
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/mmtitle_bg_alpha" >
<Button
android:id="@+id/button_back"
android:layout_width="75.0dip"
android:text=" "
android:background="@drawable/mm_title_back_btn"
android:textColor="@android:color/white"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="2dip" />
<TextView
android:id="@+id/textview_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button_back"
android:layout_alignBottom="@+id/button_back"
android:layout_centerHorizontal="true"
android:gravity="center_vertical"
android:text=" "
android:textColor="@android:color/white"
android:textSize="18sp" />
</RelativeLayout>
이 demo 안에 메 인 인터페이스 MainActivity 가 있 습 니 다.그 안에 Button,ImageView 와 TextView 가 있 습 니 다.Button 을 누 르 면 QR 코드 스 캔 인터페이스 에 들 어 갑 니 다.OK 를 스 캔 할 때 메 인 인터페이스 로 돌아 가 스 캔 결 과 를 TextView 에 표시 하고 그림 을 ImageView 에 표시 한 다음 에 그림 을 처리 하지 않 아 도 됩 니 다.제 가 가지 고 있 는 것 에 그림 을 추가 할 수 있 습 니 다.메 인 인터페이스의 구 조 는 매우 간단 하 다.다음 과 같다.
<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:background="#ffe1e0de" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text=" " />
<TextView
android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:lines="2"
android:gravity="center_horizontal"
android:textColor="@android:color/black"
android:textSize="16sp" />
<ImageView
android:id="@+id/qrcode_bitmap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_below="@+id/result"/>
</RelativeLayout>
package com.example.qr_codescan;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private final static int SCANNIN_GREQUEST_CODE = 1;
/**
*
*/
private TextView mTextView ;
/**
*
*/
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.result);
mImageView = (ImageView) findViewById(R.id.qrcode_bitmap);
// , startActivityForResult
//
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, MipcaActivityCapture.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SCANNIN_GREQUEST_CODE:
if(resultCode == RESULT_OK){
Bundle bundle = data.getExtras();
//
mTextView.setText(bundle.getString("result"));
//
mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
}
break;
}
}
}
4.567917.위의 코드 는 비교적 간단 하지만 위 챗 과 같은 스 캔 상 자 를 만 들 려 면 위 에 있 는 코드 는 그런 효과 가 없습니다.우 리 는 com.mining.app.zxing.view 가방 아래 의 ViewfinderView 류 를 다시 써 야 합 니 다.위 챗 안에 있 는 것 은 모두 사용 하 는 그림 입 니 다.저 는 제 가 그린 것 입 니 다.코드 주석 이 비교적 명확 합 니 다.여러분 은 코드 를 직접 보 세 요.이해 할 수 있 을 거 라 고 믿 습 니 다.스 캔 상자 의 크기 를 수정 하려 면 CameraManager 클래스 에서 수정 하 십시오
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mining.app.zxing.view;
import java.util.Collection;
import java.util.HashSet;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import com.example.qr_codescan.R;
import com.google.zxing.ResultPoint;
import com.mining.app.zxing.camera.CameraManager;
/**
* This view is overlaid on top of the camera preview. It adds the viewfinder
* rectangle and partial transparency outside it, as well as the laser scanner
* animation and result points.
*
*/
public final class ViewfinderView extends View {
private static final String TAG = "log";
/**
*
*/
private static final long ANIMATION_DELAY = 10L;
private static final int OPAQUE = 0xFF;
/**
*
*/
private int ScreenRate;
/**
*
*/
private static final int CORNER_WIDTH = 10;
/**
*
*/
private static final int MIDDLE_LINE_WIDTH = 6;
/**
*
*/
private static final int MIDDLE_LINE_PADDING = 5;
/**
*
*/
private static final int SPEEN_DISTANCE = 5;
/**
*
*/
private static float density;
/**
*
*/
private static final int TEXT_SIZE = 16;
/**
*
*/
private static final int TEXT_PADDING_TOP = 30;
/**
*
*/
private Paint paint;
/**
*
*/
private int slideTop;
/**
*
*/
private int slideBottom;
private Bitmap resultBitmap;
private final int maskColor;
private final int resultColor;
private final int resultPointColor;
private Collection<ResultPoint> possibleResultPoints;
private Collection<ResultPoint> lastPossibleResultPoints;
boolean isFirst;
public ViewfinderView(Context context, AttributeSet attrs) {
super(context, attrs);
density = context.getResources().getDisplayMetrics().density;
// dp
ScreenRate = (int)(20 * density);
paint = new Paint();
Resources resources = getResources();
maskColor = resources.getColor(R.color.viewfinder_mask);
resultColor = resources.getColor(R.color.result_view);
resultPointColor = resources.getColor(R.color.possible_result_points);
possibleResultPoints = new HashSet<ResultPoint>(5);
}
@Override
public void onDraw(Canvas canvas) {
// , , CameraManager
Rect frame = CameraManager.get().getFramingRect();
if (frame == null) {
return;
}
//
if(!isFirst){
isFirst = true;
slideTop = frame.top;
slideBottom = frame.bottom;
}
//
int width = canvas.getWidth();
int height = canvas.getHeight();
paint.setColor(resultBitmap != null ? resultColor : maskColor);
// , , ,
// ,
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1,
paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
if (resultBitmap != null) {
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(OPAQUE);
canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint);
} else {
// , 8
paint.setColor(Color.GREEN);
canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate,
frame.top + CORNER_WIDTH, paint);
canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top
+ ScreenRate, paint);
canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right,
frame.top + CORNER_WIDTH, paint);
canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top
+ ScreenRate, paint);
canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left
+ ScreenRate, frame.bottom, paint);
canvas.drawRect(frame.left, frame.bottom - ScreenRate,
frame.left + CORNER_WIDTH, frame.bottom, paint);
canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH,
frame.right, frame.bottom, paint);
canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate,
frame.right, frame.bottom, paint);
// , , SPEEN_DISTANCE
slideTop += SPEEN_DISTANCE;
if(slideTop >= frame.bottom){
slideTop = frame.top;
}
canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint);
//
paint.setColor(Color.WHITE);
paint.setTextSize(TEXT_SIZE * density);
paint.setAlpha(0x40);
paint.setTypeface(Typeface.create("System", Typeface.BOLD));
canvas.drawText(getResources().getString(R.string.scan_text), frame.left, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint);
Collection<ResultPoint> currentPossible = possibleResultPoints;
Collection<ResultPoint> currentLast = lastPossibleResultPoints;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
} else {
possibleResultPoints = new HashSet<ResultPoint>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(OPAQUE);
paint.setColor(resultPointColor);
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frame.left + point.getX(), frame.top
+ point.getY(), 6.0f, paint);
}
}
if (currentLast != null) {
paint.setAlpha(OPAQUE / 2);
paint.setColor(resultPointColor);
for (ResultPoint point : currentLast) {
canvas.drawCircle(frame.left + point.getX(), frame.top
+ point.getY(), 3.0f, paint);
}
}
// ,
postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,
frame.right, frame.bottom);
}
}
public void drawViewfinder() {
resultBitmap = null;
invalidate();
}
/**
* Draw a bitmap with the result points highlighted instead of the live
* scanning display.
*
* @param barcode
* An image of the decoded barcode.
*/
public void drawResultBitmap(Bitmap barcode) {
resultBitmap = barcode;
invalidate();
}
public void addPossibleResultPoint(ResultPoint point) {
possibleResultPoints.add(point);
}
}
위의 코드 에서 중간 에 있 는 그 선 위 챗 은 그림 을 사용 합 니 다.저 는 그림 을 그 렸 습 니 다.만약 에 더 시 뮬 레이 션 하고 싶 으 면 아래 코드 를...
canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint);
...로 바꾸다
Rect lineRect = new Rect();
lineRect.left = frame.left;
lineRect.right = frame.right;
lineRect.top = slideTop;
lineRect.bottom = slideTop + 18;
canvas.drawBitmap(((BitmapDrawable)(getResources().getDrawable(R.drawable.qrcode_scan_line))).getBitmap(), null, lineRect, paint);
그 스캐닝 라인 은 스스로 위 챗 에 가서 찾 아 보 세 요.제 가 붙 인 오류 가 발생 했 습 니 다.위 챗 apk 를 다운로드 하고 접미사 이름 을 zip 로 바 꾼 다음 에 압축 을 풀 면 됩 니 다.스 캔 상자 아래 글꼴 의 코드 를 수정 해 야 합 니 다.이 모양 은 글꼴 에 따라 자동 으로 중간 에 배열 할 수 있 습 니 다.만약 글자 가 너무 길 면 제 가 처리 하지 않 으 면 자동 으로 줄 을 바 꿔 야 합 니 다.당신 은 스스로 처리 할 수 있 습 니 다.
paint.setColor(Color.WHITE);
paint.setTextSize(TEXT_SIZE * density);
paint.setAlpha(0x40);
paint.setTypeface(Typeface.DEFAULT_BOLD);
String text = getResources().getString(R.string.R.string.scan_text);
float textWidth = paint.measureText(text);
canvas.drawText(text, (width - textWidth)/2, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint)
화면 캡 처 를 실행 합 니 다.그 중에서 중간 에 있 는 녹색 선 은 상하 로 이동 합 니 다.위 챗 과 의 효과 가 많 지 않 습 니 다.물론 실행 에 대응 하 는 권한 문제 가 필요 합 니 다.관심 이 있 는 친 구 는 demo 를 다운로드 할 수 있 습 니 다.8 시 에 이 블 로 그 를 많이 써 서 지금까지 이렇게 글 씨 를 쓰 는 것 처럼 보이 지만 사실은 시간 이 많이 걸 립 니 다.만약 에 이 글 이 당신 에 게 도움 이 된다 고 생각 되면 대 들 어 보 세 요.하하,목욕 을 하고 잠 을 잤 습 니 다.위의 항목 중 에 제 가 붙 이지 못 한 자원 파일 이 있 습 니 다.효 과 를 보고 싶 으 면 소스 코드 를 다운로드 할 수 있 습 니 다.
저 는 Android 에서 google Zxing 을 바탕 으로 핸드폰 에 있 는 QR 코드 를 스 캔 했 습 니 다.이 글 에서 핸드폰 에 있 는 QR 코드 사진 에 대한 스 캔 을 실 현 했 고 중간 스 캔 라인 을 바 꾸 었 습 니 다.위 챗 효과 와 더욱 비슷 합 니 다.그 글 의 프로젝트 소스 코드 를 내 려 보 시 는 것 을 권장 합 니 다.
프로젝트 소스 코드
위 에서 말 한 것 은 소 편 이 소개 한 안 드 로 이 드 가 구 글 Zxing 을 바탕 으로 QR 코드,바코드 스 캔 을 실현 하고 위 챗 QR 코드 스 캔 효 과 를 모방 하여 여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 저 에 게 메 시 지 를 남 겨 주세요.소 편 은 신속하게 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Lighthouse에서 파일 전송량이 얼마나 많았는지 알아보기Chrome에서 사용할 수 있는 Lighthouse의 기능이 최근 Google I/O로 업데이트되었습니다. Performance Budget이라고 하는 HTML/CSS/Javascipt/image등의 파일 전송 용량...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.