题目:在 Android 平台绘制一张图片,使用至少 3 种不同的 API,ImageView,SurfaceView,自定义 View
这儿只记录下用SurfaceView绘制图片的过程
自定义MySurfaceView
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable{
private SurfaceHolder mHolder;
//用于绘图的canvs
private Canvas canvas;
//子线程标志位
private boolean isDrawing;
//画笔
private Paint paint;
//原图
private Bitmap bitmap;
//指定显示的宽
private int w;
//指定显示的高
private int h;
private void init(){
mHolder = getHolder();
mHolder.addCallback(this);
// setFocusable(true);
// setFocusableInTouchMode(true);
// this.setKeepScreenOn(true);
paint = new Paint();
}
public MySurfaceView(Context context) {
super(context);
init();
}
public MySurfaceView (Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MySurfaceView (Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/**
* 绘制时,充分利用 SurfaceView 的三个回调方法,
* 在 surfaceCreated() 方法里开启子线程进行绘制,而子线程使用一个 while (mIsDrawing) {} 的循环来不停地进行绘制,
* 而在绘制的具体逻辑中,通过 lockCanvas() 方法来获取 Canvas 对象来绘制,
* 并通过 unlockCanvasAndPost(mCanvas) 方法对画布内容进行提交。
*/
@Override
public void surfaceCreated(SurfaceHolder holder) {
isDrawing = true;
new Thread(this).run();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
isDrawing = false;
}
@Override
public void run() {
draw();
}
private void draw() {
try {
canvas = mHolder.lockCanvas();
if (bitmap!=null){
Matrix matrix = new Matrix();
float scaleWidth = ((float) w)/bitmap.getWidth();
float scaleHeight = ((float) h)/bitmap.getHeight();
matrix.postScale(scaleWidth,scaleHeight);
Bitmap newBitMap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(), bitmap.getHeight(),matrix,true);
canvas.drawBitmap(newBitMap,0,0,paint);
}
}catch (Exception e){
}finally {
if (null != canvas){
/**
* 将 mHolder.unlockCanvasAndPost(mCanvas);方法放到 finally 代码块中,保证每次都能将内容提交。
*/
mHolder.unlockCanvasAndPost(canvas);
}
}
}
public void setBitmap(Bitmap img,int x,int y){
if (img!=null){
bitmap = img;
w = x;
h = y;
}
}
}
MainActivity中的内容
mSv = findViewById(R.id.sv);
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.img1);
mSv.setBitmap(bitmap,1080,488);
image.png结果
网友评论