void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)
Draw the specified bitmap, scaling/translating automatically to fill the destination rectangle.
绘制指定的位图,自动缩放/平移以填充目标矩形。没有返回值。该方法有三个参数,分别是:
Bitmap bitmap:要绘制的位图
Rect src:要绘制的位图区域,可以为空,如果为空就是绘制的区域就是这个bitmap大小。
Rect dst:绘制后的位图自动缩放/平移在dst区域展示出来。
如何使用:
需求:图片右下角的四分之一部分,显示到左上角(300,300),右下角(600,600)的矩形里面。
关键代码:
var src = Rect(mBitmap.width / 2,mBitmap.height / 2,mBitmap.width,mBitmap.height)
var dst = Rect(300,300,600,600)
完整代码:
package com.lxm.apipro.canvas.d7
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
class CanvasView : View {
private var mContext: Context? = null
private var mBitmap: Bitmap =
BitmapFactory.decodeResource(resources, com.lxm.apipro.R.drawable.pic1)
private var mPaint: Paint = Paint()
constructor(context: Context?) : this(context, null)
constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
mContext = context
}
init {
mPaint.isAntiAlias = true
mPaint.color = Color.RED
mPaint.style = Paint.Style.STROKE
mPaint.strokeWidth = 5f
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.save()
var src = Rect(mBitmap.width / 2,mBitmap.height / 2,mBitmap.width,mBitmap.height)
var dst = Rect(300,300,600,600)
canvas?.drawBitmap(mBitmap, src,dst, mPaint)
canvas?.restore()
}
}
效果图: