💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
可以通过颜色数组来创建一个Bitmap图像,对应的API接口: ~~~ public static Bitmap createBitmap(@NonNull @ColorInt int[] colors, int width, int height, Config config) { return createBitmap(null, colors, 0, width, width, height, config); } ~~~ 比如下面的案例: ~~~ class CreateBitmapDemo : View { constructor(context: Context?) : super(context) { init() } constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) { init() } constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { init() } private lateinit var mPaint: Paint private lateinit var mBitmap: Bitmap private fun init() { // 关闭硬件加速 setLayerType(LAYER_TYPE_SOFTWARE, null) // 载入图像 mBitmap = createBitmapImage(dp2px(200)) mPaint = Paint(Paint.ANTI_ALIAS_FLAG) mPaint.color = resources.getColor(R.color.teal_700, null) mPaint.style = Paint.Style.FILL_AND_STROKE } /** * 创建Bitmap图像 * @param size 正方形的图像大小 */ private fun createBitmapImage(size: Int): Bitmap{ // 根据大小初始化颜色数组 val colors = Array<Int>(size = size * size, init = { 0 }) val scale = 255f / size for (i in 0 until size){ for (j in 0 until size){ val r = (i * scale).toInt() val g = (j * scale).toInt() val b = 255 - max(r, g) val a = min(r, g) colors[i*size+j] = Color.argb(a, r, g, b) } } return Bitmap.createBitmap(colors.toIntArray(), size, size, Bitmap.Config.ARGB_8888) } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) canvas?.apply { drawBitmap(mBitmap, 0f, 0f, mPaint) } } private fun dp2px(value: Int): Int { return (resources.displayMetrics.density * value).toInt() } } ~~~ 结果: ![](https://img.kancloud.cn/0d/39/0d390780a7b68c04a9b8c86da12725c0_256x225.png)