Android自定義surfaceView顯示多張圖片

jopen 12年前發布 | 65K 次閱讀 Android Android開發 移動開發

我自定義了一個surfaceview,我在上面繪制多張圖片,讓它能夠上下方滾顯示圖片,但是onMeasure()方法在重寫的時候遇到了問題,不知道如何設置它的高度,

public class MySurfaceView extends SurfaceView implements Callback{

private SurfaceHolder sfh;
private Paint paint;
public MySurfaceView(Context context) {
    super(context);
    init(context);
}



private void init(Context context) {
    sfh=this.getHolder();
    sfh.addCallback(this);
    paint=new Paint();
    paint.setColor(Color.WHITE);

}



public MySurfaceView(Context context, AttributeSet attrs, int defStyle) {
    super(context,attrs,defStyle);
    init(context);
}



public MySurfaceView(Context context, AttributeSet attrs) {
    super(context,attrs);
    init(context);

}



@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    myDraw();
}

private void myDraw() {
    Canvas canvas=sfh.lockCanvas();
    canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), new Paint());
    Bitmap bmp=readBitmap(getResources(), R.drawable.pic0);
    Matrix matrix=new Matrix();

    matrix.setScale(0.15f, 0.15f);
    matrix.postTranslate(100, 0);
    canvas.drawBitmap(bmp, matrix, paint);

    matrix.postTranslate(0, 450);
    bmp=readBitmap(getResources(), R.drawable.pic2);
    canvas.drawBitmap(bmp, matrix, paint);

    matrix.postTranslate(0, 500);
    bmp=readBitmap(getResources(), R.drawable.pic5);
    canvas.drawBitmap(bmp, matrix, paint);

    matrix.postTranslate(0, 550);
    bmp=readBitmap(getResources(), R.drawable.pic7);
    canvas.drawBitmap(bmp, matrix, paint);

    sfh.unlockCanvasAndPost(canvas);
    if(bmp!=null)
    bmp.recycle();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return super.onTouchEvent(event);
}


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // TODO Auto-generated method stub
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    setMeasuredDimension(800, 2000);//2:5   2000 5000   1600 4000  2:5
}


public static Bitmap readBitmap(Resources r, int resId) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
InputStream is = r.openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opt);
}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!