在Android中绘制位图部分?

时间:2012-11-23 01:38:01

标签: java android graphics

我这里有一个在Android中绘制旋转缩放位图的方法:

public void drawRotatedScaledBitmap(Bitmap b, 
        float centerX, float centerY, float width, float height, float angle)
{
    float scaleX = width / b.getWidth();
    float scaleY = height / b.getHeight();
    centerX -= (b.getWidth() * scaleX) / 2.0f;
    centerY -= (b.getHeight() * scaleY) / 2.0f;
    matrix.reset();
    matrix.setTranslate(centerX, centerY);
    matrix.postRotate(angle * (180.0f / (float)(Math.PI)),
            centerX + (b.getWidth() * scaleX) / 2.0f,
            centerY + (b.getHeight() * scaleY) / 2.0f); 
    matrix.preScale(scaleX,scaleY);
    canvas.drawBitmap(b, matrix, null);
}

我不知道如何修改它以获取float sourceX,float sourceY,float sourceW,float sourceH。

我想渲染图块集,所以我需要告诉它在位图上说64,64,64,64。

我怎么能这样做?

由于

2 个答案:

答案 0 :(得分:0)

也许您可以尝试使用canvas.clipRect()来指定绘图区域。

答案 1 :(得分:0)

以下是我解决它的方法:

public void drawRotatedScaledBitmap(Bitmap b, 
        float centerX, float centerY, float width, float height,
        float sourceX, float sourceY, 
        float sourceWidth, float sourceHeight, float angle)
{
    float cx = centerX;
    float cy = centerY;

    dstRect.left = (int)centerX - (int)(width / 2);
    dstRect.top = (int)centerY - (int)(height / 2);
    dstRect.right = dstRect.left +  (int)width;
    dstRect.bottom = dstRect.top +  (int)height;

    srcRect.left = (int)sourceX;
    srcRect.top = (int)sourceY;
    srcRect.right = srcRect.left +  (int)sourceWidth;
    srcRect.bottom = srcRect.top +  (int)sourceHeight;

    canvas.rotate(angle * (180.0f / (float)(Math.PI)),cx,cy);
    canvas.drawBitmap(b, srcRect, dstRect, null);
    canvas.rotate(-angle * (180.0f / (float)(Math.PI)),cx,cy);
}