Last active
July 23, 2018 09:29
-
-
Save rostopira/97ddc92d7bb804e1616c310c7a7a5cfa to your computer and use it in GitHub Desktop.
Simple QRView for Android using ZXING
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.graphics.* | |
import android.os.Build | |
import android.view.View | |
import com.google.zxing.BarcodeFormat | |
import com.google.zxing.EncodeHintType | |
import com.google.zxing.qrcode.QRCodeWriter | |
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel | |
import java.util.* | |
class QrView(ctx: Context): View(ctx) { | |
private val paint = Paint().apply { | |
isDither = false | |
isAntiAlias = false | |
color = Color.BLACK | |
} | |
private var bitmap: Bitmap? = null | |
private val srcRect = Rect() | |
private val dstRect = Rect() | |
var text: String? = null | |
set(value) { | |
if (field == value) | |
return | |
field = value | |
bitmap?.recycle() | |
bitmap = null | |
invalidate() | |
} | |
var color: Int = Color.BLACK | |
set(value) { | |
field = value | |
paint.color = value // For ALHA_8 | |
paint.colorFilter = PorterDuffColorFilter(value, PorterDuff.Mode.SRC_ATOP) // For ARGB_8888 | |
invalidate() | |
} | |
override fun onDraw(canvas: Canvas) { | |
val text = text ?: return | |
if (text.isEmpty()) return | |
val bitmap = bitmap ?: generateQr(text) | |
srcRect.right = bitmap.width | |
srcRect.bottom = bitmap.height | |
val sz = Math.min(canvas.width, canvas.height) | |
dstRect.right = sz | |
dstRect.bottom = sz | |
canvas.drawBitmap(bitmap, srcRect, dstRect, paint) | |
} | |
companion object { | |
private fun generateQr(text: String): Bitmap { | |
val hintMap = Hashtable<EncodeHintType, ErrorCorrectionLevel>() | |
hintMap[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H | |
val qrw = QRCodeWriter() | |
val bitMatrix = qrw.encode(text, BarcodeFormat.QR_CODE, 0, 0) | |
val size = bitMatrix.width | |
val pixels = IntArray(size * size) { | |
if (bitMatrix[it / size, it % size]) | |
Color.BLACK | |
else | |
Color.TRANSPARENT | |
} | |
// ALPHA_8 doesn't worked for me on 5.1, but worked on 8.0 and 8.1 | |
// I dunno why, so here we go | |
return Bitmap.createBitmap(pixels, size, size, | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) | |
Bitmap.Config.ALPHA_8 | |
else | |
Bitmap.Config.ARGB_8888 | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment