【问题标题】:Drawing bitmap to the size of the canvas将位图绘制到画布的大小
【发布时间】:2015-11-18 08:07:53
【问题描述】:

我有需要绘制到画布上的位图。图像是固定大小的,但画布会根据用户的屏幕大小和密度而变化(位图比画布更大/更小)。

我需要将位图绘制到画布,一直缩放到画布大小(不扭曲图像),我已经完成了如下代码,但位图仍然只填充了屏幕的一部分。

Rect dest = new Rect(0, 0, drawCanvas.getWidth(), drawCanvas.getHeight());
Paint paint = new Paint();
paint.setFilterBitmap(true);
drawCanvas.drawBitmap(canvasBitmap, null, dest, paint);

我可以知道是否有人可以阐明一个好的解决方案吗?谢谢。

【问题讨论】:

    标签: android bitmap android-canvas


    【解决方案1】:

    这个例子是用 javascript 编写的,但它仍然可以帮助你缩放图像

    jsFiddle:https://jsfiddle.net/CanvasCode/7oghuwe2/3/

    javascript

    var canvas1 = document.getElementById('canvas1');
    var context1 = canvas1.getContext('2d')
    var canvas2 = document.getElementById('canvas2');
    var context2 = canvas2.getContext('2d');
    
    var image1 = new Image();
    image1.src = "http://media.giphy.com/media/iNk83OBPzlA8o/giphy.gif";
    
    image1.onload = function () {
        context1.fillStyle = "#F00";
        context1.fillRect(0, 0, canvas1.width, canvas1.height);
        context2.fillStyle = "#00F";
        context2.fillRect(0, 0, canvas2.width, canvas2.height);
        ratio(context1, canvas1, image1);
        ratio(context2, canvas2, image1);
    }
    
    function ratio(context1, canvas1, image1) {
        var imageRatio = image1.width / image1.height;
    
        var newHeight = canvas1.width / imageRatio;
        var newWidth = canvas1.height * imageRatio;
    
        var heightDiff = newHeight - canvas1.height;
        var widthDiff = newWidth - canvas1.width;
    
        if (widthDiff >= heightDiff) {
            context1.drawImage(image1, 0, 0, canvas1.width, canvas1.width / imageRatio);
        } else {
            context1.drawImage(image1, 0, 0, canvas1.height * imageRatio, canvas1.height);
        }
    }
    

    基本上,如果您按画布高度缩放图像,您需要计算宽度是多少,如果您按画布宽度缩放图像,高度会是多少,并且哪个更小,然后按该尺寸进行缩放.

    【讨论】:

      【解决方案2】:

      它可能对您不起作用的原因可能是因为函数drawBitmap() 忽略了位图的密度。以下来自documentation

      public void drawBitmap (Bitmap bitmap, Rect src, Rect dst, Paint 油漆)

      此函数忽略与位图相关的密度。这是 因为源和目标矩形坐标空间在 他们各自的密度,所以必须已经有适当的 应用了比例因子。


      您可以做的是改用public void drawBitmap (Bitmap bitmap, Matrix matrix, Paint paint)。首先,您需要将源矩阵与目标矩阵映射。您可以通过Matrix.setRectToRect()Matrix.setPolyToPoly() 执行此操作。这将为您提供准确的映射。只要确保你正确地映射它们,否则事情会被扭曲。

      更多信息请参考这里:What code should I use with 'drawMatrix.setPolyToPoly' to manipulate and draw just a rectangular part of a bitmap, rather than the entire bitmap?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-06
        • 2020-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-22
        相关资源
        最近更新 更多