Android 는 google Zxing 을 바탕 으로 각종 QR 코드 스 캔 효 과 를 실현 합 니 다.

20249 단어 androidQR 코드Zxing
위 챗 이 도착 하면 서 QR 코드 가 점점 뜨 거 워 지고 곳곳에서 QR 코드 를 볼 수 있 습 니 다.예 를 들 어 쇼핑 몰,KFC,식당 등 이 있 습 니 다.QR 코드 스 캔 에 대해 저 희 는 구 글 의 오픈 소스 프레임 워 크 Zxing 을 사 용 했 습 니 다.저 희 는 소스 코드 와 Jar 가방 을 다운로드 할 수 있 습 니 다.예전 에 제 항목 의 QR 코드 스 캔 기능 은 스 캔 기능 만 실 현 했 습 니 다.그 UI 는 정말 못 생 겼 습 니 다.좋 은 애플 리 케 이 션 은 그 UI 인터페이스 도 대중 에 게 받 아들 여야 한다.그렇지 않 으 면 사람들 이 너의 소프트웨어 를 사용 하지 않 을 것 이다.그래서 애플 리 케 이 션 기능 과 인터페이스 가 모두 중요 하 다.예 를 들 어 위 챗,위 챗 UI 가 많은 애플 리 케 이 션 에 의 해 모방 되 었 다 고 믿는다.나 도 위 챗 스 캔 2 차원 코드 효 과 를 모방 하여 모방 했다.위 챗 이 그렇게 정교 하 게 만 들 지 는 않 았 지만 효 과 는 괜 찮 았 다.그래서 자신 이 수정 한 UI 코드 와 QR 코드 를 스 캔 한 코드 를 여러분 에 게 공유 합 니 다.첫째,자신 이 프로젝트 에서 똑 같은 기능 을 만 나 직접 복사 해서 사용 하 는 것 입 니 다.둘째,QR 코드 기능 을 추가 하지 않 은 사람 에 게 참고 하 는 것 입 니 다.거인 의 어깨 위 에 서 있 습 니 다.하하,저도 거인 의 어깨 위 에 서서 이 기능 을 추 가 했 습 니 다.그 다음 에 저 를 따라 이 기능 을 실현 하 겠 습 니 다.안 에는 불필요 한 파일 들 이 많이 제거 되 어 있 습 니 다.
우 리 는 먼저 프로젝트 의 구 조 를 살 펴 보 자.
  • 만약 에 프로젝트 도 이 기능 에 가입 하고 싶다 면 com.mining.app.zxing.camera,com.mining.app.zxing.decoding,com.mining.app.zxing.view 이 세 개의 가방 을 프로젝트 에 복사 한 다음 에 해당 하 는 자원 을 도입 하 세 요.저도 제 프로젝트 에서 직접 인용 한 것 입 니 다.가방 이름 도 바 뀌 지 않 았 습 니 다.물론 Zxing.jar 를 인용 해 야 합 니 다.
  • com.example.qr_codescan 패키지 안에 Mipca Activity Capture 가 있 고 제 이전 프로젝트 의 코드 를 직접 도입 한 것 입 니 다.이 Activity 는 주로 스 캔 인터페이스 의 종 류 를 처리 합 니 다.예 를 들 어 스 캔 에 성공 하면 소리 와 진동 등 이 있 습 니 다.주로 안에 있 는 handle Decode(Result result,Bitmap barcode)방법 에 관심 을 가 집 니 다.스 캔 이 끝 난 후에 스 캔 한 결과 와 QR 코드 의 bitmap 인 자 를 handle Decode(Result result,Bitmap barcode)에 전달 합 니 다.저 희 는 그 안에 해당 하 는 처리 코드 만 쓰 면 됩 니 다.다른 곳 은 고 칠 필요 가 없습니다.저 는 스 캔 결과 와 스 캔 한 사진 을 처리 합 니 다.
  • 
    /** 
     *        
     * @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(); 
    } 
    
    저 는 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> 
    
    안에서 나 는 인터페이스 위의 부분 을 다른 레이아웃 에 쓰 고 include 를 들 어 왔 다.왜냐하면 이 activitytitle 은 제 프로젝트 에서 다른 Activity 에서 도 사용 할 수 있 습 니 다.저도 직접 복사 한 것 입 니 다.
    
    <?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> 
    
    MainActivity 안의 코드 는 다음 과 같 습 니 다.안의 기능 은 위 에서 이미 말 했 습 니 다.
    
    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; 
      } 
     }  
     
    } 
    
    위의 코드 는 비교적 간단 하지만 위 챗 과 같은 스 캔 상 자 를 만 들 려 면 위 에 있 는 코드 는 그런 효과 가 없습니다.우 리 는 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 
     * 
     *  * 
     * 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) 
    인터페이스 캡 처 를 실행 합 니 다.그 중에서 중간 에 있 는 녹색 선 은 상하 로 이동 합 니 다.위 챗 과 의 효과 가 많 지 않 습 니 다.물론 실행 에 대응 하 는 권한 문제 가 필요 합 니 다.



    여러분 은 주 제 를 참고 하여 학습 할 수 있 습 니 다.
    이상 은 본 고의 모든 내용 입 니 다.여러분 이 안 드 로 이 드 소프트웨어 프로 그래 밍 을 배 우 는 데 도움 이 되 기 를 바 랍 니 다.

    좋은 웹페이지 즐겨찾기