可以通過顏色數組來創建一個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()
}
}
~~~
結果:

- 介紹
- UI
- MaterialButton
- MaterialButtonToggleGroup
- 字體相關設置
- Material Design
- Toolbar
- 下拉刷新
- 可折疊式標題欄
- 懸浮按鈕
- 滑動菜單DrawerLayout
- NavigationView
- 可交互提示
- CoordinatorLayout
- 卡片式布局
- 搜索框SearchView
- 自定義View
- 簡單封裝單選
- RecyclerView
- xml設置點擊樣式
- adb
- 連接真機
- 小技巧
- 通過字符串ID獲取資源
- 自定義View組件
- 使用系統控件重新組合
- 旋轉菜單
- 輪播圖
- 下拉輸入框
- 自定義VIew
- 圖片組合的開關按鈕
- 自定義ViewPager
- 聯系人快速索引案例
- 使用ListView定義側滑菜單
- 下拉粘黏效果
- 滑動沖突
- 滑動沖突之非同向沖突
- onMeasure
- 繪制字體
- 設置畫筆Paint
- 貝賽爾曲線
- Invalidate和PostInvalidate
- super.onTouchEvent(event)?
- setShadowLayer與陰影效果
- Shader
- ImageView的scaleType屬性
- 漸變
- LinearGradient
- 圖像混合模式
- PorterDuffXfermode
- 橡皮擦效果
- Matrix
- 離屏繪制
- Canvas和圖層
- Canvas簡介
- Canvas中常用操作總結
- Shape
- 圓角屬性
- Android常見動畫
- Android動畫簡介
- View動畫
- 自定義View動畫
- View動畫的特殊使用場景
- LayoutAnimation
- Activity的切換轉場效果
- 屬性動畫
- 幀動畫
- 屬性動畫監聽
- 插值器和估值器
- 工具
- dp和px的轉換
- 獲取屏幕寬高
- JNI
- javah命令
- C和Java相互調用
- WebView
- Android Studio快捷鍵
- Bitmap和Drawable圖像
- Bitmap簡要介紹
- 圖片縮放和裁剪效果
- 創建指定顏色的Bitmap圖像
- Gradle本地倉庫
- Gradle小技巧
- RxJava+Okhttp+Retrofit構建網絡模塊
- 服務器相關配置
- node環境配置
- 3D特效