2015-11-18 33 views
0

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

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

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

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

回答

0

这个例子是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); 
    } 
} 

基本上你需要计算的宽度会是什么,如果你通过画布高度缩放图像,如果您通过画布宽度缩放图像,并且哪个更小,然后按该维度缩放,则高度将会是多少。

0

它可能不适合你的原因可能是因为功能drawBitmap()忽略了位图的密度密度。以下是来自documentation

公共无效drawBitmap(位图的位图,矩形的src,dst的矩形,油漆 漆)

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


你可以做的是用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?