我正在为画布创建背景,但无法让图像适合屏幕,它只显示图像的中心部分。我尝试过createScaledBitmap调用显示指标但没有成功,还在drawBitmap中调用了Rect和ReEctF,我不知道我做错了什么。
class DrawStars(context: Context): View(context) {
private var posX = 500f
private var posY = 800f
private var drawcolor: Int = ResourcesCompat.getColor(resources, R.color.black, null)
private val paint = Paint().apply{
color = drawcolor
style = Paint.Style.STROKE
isAntiAlias = true
}
val dm = resources.displayMetrics
val fwidth = dm.density * dm.widthPixels
val fheight = dm.density * dm.heightPixels
private var background = BitmapFactory.decodeResource(resources, R.drawable.fondo_sector2)
//var resized: Bitmap = Bitmap.createScaledBitmap(background, fwidth.toInt(), fheight.toInt(), true)
private var bitmap1 = BitmapFactory.decodeResource(resources, R.drawable.star1)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawBitmap(background, 0f, 0f, paint)
//canvas.drawBitmap(resized, 0f, 0f, paint)
canvas.drawBitmap(bitmap1, posX, posY, paint)
}
}`
技巧是使用createScaledBitmap,我不确定这是否是正确的解决方案,但至少它有效。
private val bar = getActionBarHeight()
private val dm: DisplayMetrics = resources.displayMetrics
private var bitmap = BitmapFactory.decodeResource(resources, R.drawable.fondo_sector)
private val background = Bitmap.createScaledBitmap(
bitmap, dm.widthPixels, dm.heightPixels + bar, true)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawBitmap(background, 0f, 0f, p)
}
最后,隐藏操作栏
private fun getActionBarHeight(): Int {
// Height of action bar
val ta = context.theme.obtainStyledAttributes(
intArrayOf(android.R.attr.actionBarSize)
)
val actionBarHeight = ta.getDimension(0, 0f).toInt()
return actionBarHeight
}