Created
October 4, 2019 13:31
-
-
Save NickHolcombe/017a49802b9f52e71a488633b56e5e1b to your computer and use it in GitHub Desktop.
Barcode blog MainActivity.kt
This file contains 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
package uk.co.brightec.barcodeblogpost | |
import android.graphics.Bitmap | |
import android.os.Bundle | |
import androidx.annotation.ColorInt | |
import androidx.appcompat.app.AppCompatActivity | |
import com.google.zxing.BarcodeFormat | |
import com.google.zxing.oned.Code128Writer | |
import kotlinx.android.synthetic.main.activity_main.* | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
displayBitmap("9781407189178") | |
} | |
private fun displayBitmap(value: String) { | |
val widthPixels = resources.getDimensionPixelSize(R.dimen.width_barcode) | |
val heightPixels = resources.getDimensionPixelSize(R.dimen.height_barcode) | |
image_barcode.setImageBitmap( | |
createBarcodeBitmap( | |
barcodeValue = value, | |
barcodeColor = getColor(R.color.colorPrimary), | |
backgroundColor = getColor(android.R.color.white), | |
widthPixels = widthPixels, | |
heightPixels = heightPixels | |
) | |
) | |
text_barcode_number.text = value | |
} | |
private fun createBarcodeBitmap( | |
barcodeValue: String, | |
@ColorInt barcodeColor: Int, | |
@ColorInt backgroundColor: Int, | |
widthPixels: Int, | |
heightPixels: Int | |
): Bitmap { | |
val bitMatrix = Code128Writer().encode( | |
barcodeValue, | |
BarcodeFormat.CODE_128, | |
widthPixels, | |
heightPixels | |
) | |
val pixels = IntArray(bitMatrix.width * bitMatrix.height) | |
for (y in 0 until bitMatrix.height) { | |
val offset = y * bitMatrix.width | |
for (x in 0 until bitMatrix.width) { | |
pixels[offset + x] = | |
if (bitMatrix.get(x, y)) barcodeColor else backgroundColor | |
} | |
} | |
val bitmap = Bitmap.createBitmap( | |
bitMatrix.width, | |
bitMatrix.height, | |
Bitmap.Config.ARGB_8888 | |
) | |
bitmap.setPixels( | |
pixels, | |
0, | |
bitMatrix.width, | |
0, | |
0, | |
bitMatrix.width, | |
bitMatrix.height | |
) | |
return bitmap | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment