1

我正在寻找一个真实示例,其中包含有关如何在大于屏幕尺寸的画布上绘制的示例代码(截至目前,我正在正常绘制并且无法查看外部屏幕尺寸)。更多的压力在于能够滚动/平移屏幕以查看整个画布。如果需要更多信息,请发表评论。

更新:在这里找到我的答案Image in Canvas with touch events

4

3 回答 3

4

我的版本是从 Monodroid 转换而来的,但实现看起来应该差不多。(我试着把它放回java,如果不准确,请道歉)

  1. 为了在屏幕外绘制,只需在您想要的任何地方绘制,它将被绘制到屏幕外。诀窍是通过缩放和平移来查看它。要缩放您的视图,需要实现 ScaleGestureDetector.IOnScaleGestureListener 并实现 onScale 方法,如下所示。

  2. 对于平移,您只需要实现 onTouchEvent,无论如何缩放都是必需的。

    private float _scaleFactor;
    private float _xoffset;
    private float _yoffset;
    
    @override
    public bool onScale(ScaleGestureDetector detector){
        _scaleFactor *= detector.ScaleFactor;
        _scaleFactor = Math.Max(0.1f, Math.Min(_scaleFactor, 5.0f));
        invalidate();
        return true;
    } 
    
    @override 
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        canvas.save();
        canvas.scale(_scaleFactor, _scaleFactor);//for zoom
        canvas.translate(_xoffset, _yoffset);//for pan
        //DO NORMAL DRAWING HERE
        canvas.restore();
    }
    
    @override 
    public bool onTouchEvent(MotionEvent e){
        switch (e.action){
            case MotionEvent.ACTION_DOWN:{                        
                _prevx = e.getX();
                _prevy = e.getY();
            }
            break;
            case MotionEvent.ACTION_UP:{
                _xoffset += e.getX() - _prevx;
                _yoffset += e.getY() - _prevy;
                invalidate();
    
                _prevx = e.getX();
                _prevy = e.getY();
            }
            break;
        }
        return _scaleGestureDetector.onTouchEvent(e);
    }
    

注意:此代码用于自定义 VIEW 对象 - 因此从 View 继承并实现 IOnScaleGestureListener

于 2012-07-09T15:32:10.550 回答
1

您可以简单地将整个画布放在ScrollView中。这样,Android 会为您处理所有滚动。但是,如果您希望能够让用户与 Canvas 进行交互而不是滚动,则需要拦截来自 ScrollView 的一些触摸事件。可以在此处找到执行此操作的示例。

于 2012-07-09T15:14:11.437 回答
1
@Override
public void onCreate(Bundle savedInstanceState)
{
    CustomView customView;
    ScrollView scroll_view;
    HorizontalScrollView h_scroll_view;
    super.onCreate(savedInstanceState);
    scroll_view = new ScrollView(this);
    h_scroll_view = new HorizontalScrollView(this);
    customView = new CustomView(this);

    scroll_view.addView(customView);
    h_scroll_view.addView(scroll_view);
    setContentView(h_scroll_view);
}


public class CustomView extends View
{
    private Paint paint;
    Context app_context;

    public CustomView(Context context) {
        super(context);
        paint = new Paint();
        paint.setColor(Color.GRAY);
        app_context = context;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int width = 1000;
        int height = 1200;
        setMeasuredDimension(width, height);
    }

    @Override
    public void onDraw(Canvas canvas)
    {
       // ToDo: Put drawing code in here
            }
        }
    }
}
于 2017-11-21T08:28:19.010 回答