gpt4 book ai didi

java - 在 Canvas 上仅显示图像的特定部分

转载 作者:行者123 更新时间:2023-11-30 09:59:08 26 4
gpt4 key购买 nike

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

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);
}
}

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

可视化:

I want to only draw the separated part of the image but still other objects outside the separated part

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

但是该线程仅展示了如何解决我的 ImageView 问题。有没有人有在 Canvas 中执行此操作的解决方案?

最佳答案

在 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

编码愉快!

关于java - 在 Canvas 上仅显示图像的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com