无法平移和缩放画布中的图像

发布于 2024-12-08 07:47:07 字数 1225 浏览 2 评论 0原文

我正在尝试使用画布显示图像,该画布允许缩放和平移,但会阻止用户将图像平移到屏幕外。我已经能够停止平移,但是当图片缩放时,它会停止在图像边缘之前。我需要能够平移到图像的边缘,甚至放大。任何帮助将不胜感激。

我的代码显示图像,停止屏幕外平移和缩放:

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();

        if (mPosX < displayWidth - mIcon.getIntrinsicWidth()){
            mPosX = displayWidth - mIcon.getIntrinsicWidth();}
        if (mPosX > 0){
            mPosX = 0; }
        if (mPosY < displayHeight - mIcon.getIntrinsicHeight()){
            mPosY = displayHeight - mIcon.getIntrinsicHeight();}
        if (mPosY > 0){
            mPosY = 0; }

        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        mIcon.draw(canvas);
        canvas.restore();
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();

            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(0.42f, Math.min(mScaleFactor, 5.0f));

            invalidate();
            return true;
        }
    }

I am trying to display an image with canvas that allows zoom and panning but will stop the user from panning the image off screen. I have been able to stop the panning but when the picture is zoomed it stops before the edge of the image. I need to be able to pan to the edge of the image even zoomed in. Any help would be appreciated.

My code that displays image, stops the panning offscreen and zoom:

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();

        if (mPosX < displayWidth - mIcon.getIntrinsicWidth()){
            mPosX = displayWidth - mIcon.getIntrinsicWidth();}
        if (mPosX > 0){
            mPosX = 0; }
        if (mPosY < displayHeight - mIcon.getIntrinsicHeight()){
            mPosY = displayHeight - mIcon.getIntrinsicHeight();}
        if (mPosY > 0){
            mPosY = 0; }

        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        mIcon.draw(canvas);
        canvas.restore();
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();

            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(0.42f, Math.min(mScaleFactor, 5.0f));

            invalidate();
            return true;
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文