说一个真实的案例。其中需求要做一个绘图功能,一听到绘图,自然而然就像到了SurfaceView这个类。所以我就用了。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.test.MySurfaceVivew
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
然后就是MySurfaceView继承SurfaceView,然后我们就会定义一个drawCanvas方法去绘图,通常的做法就是这样
package com.example.test;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MySurfaceVivew extends SurfaceView{
private SurfaceHolder holder;
private Bitmap bitmap;
public MySurfaceVivew(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
holder = this.getHolder();
}
private void drawCanvas(Bitmap bitmap){
Canvas canvas = holder.lockCanvas();
if(canvas != null){
canvas.drawBitmap(bitmap, 0, 0, null);
holder.unlockCanvasAndPost(canvas);
}
}
public void setBitmap(Bitmap bitmap){
this.bitmap = bitmap;
this.drawCanvas(bitmap);
}
}
通过setBitmap去加载一张图片,然后在用画布画出来。但是很不幸,现实是残酷的,当Activity加载布局时图片闪一下就黑屏了。为什么呢?查了一下资料,原来Activity在加载时后会卸载SurfaceView,在创建后很快就被卸载掉了,所以只能见到闪的一下就黑屏了。有些资料会说在onResume方法中设,我也试了一下,发现不行,这下连闪都不闪一下。调试发现,canvas画布为空。自然,黑屏也就理所当然了。那怎么办,解决问题的办法才是问题的关键。那么,我们就要在画布创建时把图片画出来。
有了突破点就好办了。canvas画布在什么时候创建,就的看他谁提供的。canvas = holder.lockCanvas(),不难看出宿主是surfaceholder。那么是不是surfaceholder被创建的同时创建了canvas呢?我做了一次尝试。
package com.example.test;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MySurfaceVivew extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder holder;
private Bitmap bitmap;
public MySurfaceVivew(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
holder = this.getHolder();
}
private void drawCanvas(Bitmap bitmap){
Canvas canvas = holder.lockCanvas();
if(canvas != null){
canvas.drawBitmap(bitmap, 0, 0, null);
holder.unlockCanvasAndPost(canvas);
}
}
public void setBitmap(Bitmap bitmap){
this.bitmap = bitmap;
this.drawCanvas(bitmap);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
this.drawCanvas(bitmap);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}