在Android中平滑地滚动画布

pre*_*bgg 24 android smooth-scrolling android-canvas

我是Android的新手.

我正在我的视图的OnDraw(Canvas画布)方法中的Canvas上绘制位图,线条和形状.我正在寻找有关如何实现平滑滚动以响应用户拖动的帮助.我已经搜索但没有找到任何教程来帮助我.

Canvas的引用似乎表明,如果Canvas是从Bitmap构建的(比方说称为bmpBuffer),那么在Canvas上绘制的任何内容也会在bmpBuffer上绘制.是否可以使用bmpBuffer来实现滚动...也许可以将它复制回Canvas一次移动几个像素?但是如果我使用Canvas.drawBitmap将bmpBuffer绘制回Canvas移动几个像素,bmpBuffer会不会被破坏?因此,也许,我应该将bmpBuffer复制到bmpBuffer2,然后将bmpBuffer2绘制回Canvas.

一个更直接的方法是将线条,形状等直接绘制到缓冲区中Bitmap然后将该缓冲区(带有移位)绘制到Canvas上,但我可以看到各种方法:drawLine(),drawShape()等等不能用于绘制到Bitmap ...仅用于Canvas.

我可以有2幅画布吗?其中一个是从缓冲区位图构造的,仅用于绘制线条,形状等,然后缓冲区位图将被绘制到另一个Canvas中以便在View中显示?

我应该欢迎任何建议!

这里(和其他网站上)类似问题的答案是指"blitting".我理解这个概念,但在Android文档中找不到关于"blit"或"bitblt"的任何内容.Canvas.drawBitmap和Bitmap.Copy是Android的等价物吗?

pre*_*bgg 12

I seem to have found an answer. I have put the bulk of the drawing code (which was previously in onDraw()) in a new doDrawing() method. This method starts by creating a new bitmap larger than the screen (large enough to hold the complete drawing). It then creates a second Canvas on which to do the detailed drawing:

    BufferBitmap = Bitmap.createBitmap(1000, 1000, Bitmap.Config.ARGB_8888);
    Canvas BufferCanvas = new Canvas(BufferBitmap);
Run Code Online (Sandbox Code Playgroud)

The rest of the doDrawing() method is taken up with detailed drawing to BufferCanvas.

The entire onDraw() method now reads as follows:

    @Override protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawBitmap(BufferBitmap, (float) -posX, (float) -posY, null);
}
Run Code Online (Sandbox Code Playgroud)

The position variables, posX and posY, are initialised at 0 in the application's onCreate()method. The application implements OnGestureListener and uses the distanceX and distanceY arguments returned in the OnScroll notification to increment posX and posY.

That seems to be about all that's needed to implement smooth scrolling. Or am I over-looking something!?


Mer*_*vin 1

我也有这个问题,

我是这样画的:

Canvas BigCanvas = new Canvas();
Bitmap BigBitmap = new Bitmap(width,height);

int ScrollPosX , ScrollPosY  // (calculate these with the onScrollEvent handler)

void onCreate()
{
   BigCanvas.SetBitmap(BigBitmap);
}

onDraw(Canvas TargetCanvas)
{
   // do drawing stuff
   // ie.  BigCanvas.Draw.... line/bitmap/anything

   //draw to the screen with the scrolloffset

   //drawBitmap (Bitmap bitmap, Rect src, Rect dst, Paint paint)
   TargetCanvas.DrawBitmap(BigBitmap(new Rect(ScrollPosX,ScrollPosY,ScrollPosX + BigBitmap.getWidth(),ScrollPosY + BigBitmap.getHeight(),new Rect(0,0,ScreenWidth,ScreenHeight),null);
}
Run Code Online (Sandbox Code Playgroud)

为了平滑滚动,您需要制定某种方法,在滚动后获取一些点(即第一个滚动点和第10个滚动点),减去这些点并在每个循环中滚动该数字,使其逐渐变慢( ScrollAmount - 转动 - 摩擦)。

我希望这能提供更多的见解。