【问题标题】:Displaying only certain part of image on a Canvas在画布上仅显示图像的特定部分
【发布时间】:2020-03-27 08:46:33
【问题描述】:

我目前正在 Android Studio 中的画布上绘制图像,如下所示:

public class Floor{
    int x;
    int y;
    int width;
    int height;
    Drawable image;

    public Floor(int x, int y, int width, int height, Context context) {
        this.x = x;
        this.y = y;
        this.height = height;
        this.width = width;
        this.image = this.context.getResources().getDrawable(R.drawable.floorimage);
    }

    // this method is called in the draw loop
    public void draw(Canvas canvas) {

        Rect imageBounds = new Rect(this.x, this.y, this.x + this.width, this.y + this.height);

        this.image.setBounds(imageBounds);
        this.image.draw(canvas);
    }
}

所以图片大小是根据宽高来设置的。 但是我不想重置图像大小,我想绘制图像的一部分,包括在宽度和高度中。

可视化:

我知道这个线程: Android - Display part of a large image

但是,该线程仅显示了如何解决 ImageView 的问题。 有没有人有在画布上执行此操作的解决方案?

【问题讨论】:

  • 你的“我想要的”图片真的不是太清晰,b/c 它只是显示图片中添加了几条黑线,但我认为你想要clipRect()
  • 不幸的是,这不是我想要的,clipRect() 确实像我想要的那样剪切了图像,但是它剪切了画布内的所有内容(我不想要那个)。我已经更新了图像,希望它更清晰。

标签: java android canvas


【解决方案1】:

在 Floor.draw() 中试试这个:

public void draw(Canvas canvas) {

 Rect canvasBounds = canvas.getClipBounds();         //get the current clip(Canvas drawing area)
 this.image.setBounds(canvasBounds);      //same bounds as canvas, so image is the same size. We clip next

 Rect imageBounds=new Rect(0,0,this.width,this.height); //You should move this line to constructor. You know, performance and all.                                                                

 canvas.save();                 //save the current clip. You can't use canvasBounds to restore it later, there is no setClipBounds()
 canvas.clipRect(imageBounds); //clip the canvas so you draw only the width and height u want
 this.image.draw(canvas);
 canvas.restore();       //restore the Canvas clip. 

 //do other drawings with full size canvas

}

编码愉快!

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 2012-12-28
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多