gpt4 book ai didi

android - 在给定矩形边界的情况下以编程方式缩放和居中 imageView

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:42 26 4
gpt4 key购买 nike

我的问题

假设我有一个位图 - 将其命名为 bmap,尺寸为 100x75 (bmap.getWidth() x bmap.getHeight())

假设我有一个矩形,rect,位于手机屏幕上的点 (x,y) 上,尺寸为 500x350(宽 x 高)

我如何编写一段代码,使该位图在边界矩形内居中。

注意:因为我使用的是 ContraintLayout,所以没有 parent 或相对论的概念。

另外,我想要一个 (0,1] 范围内的 scale 变量,它缩放 bmap 但它保持在边界矩形 rect 的中心。

我可怕的尝试:

ImageView imgView = new ImageView(this.context);
imgView.setMaxWidth((int)(width*scale));
imgView.setMinimumWidth((int)(width*scale));
imgView.setMaxHeight((int)(height*scale));
imgView.setMinimumHeight((int)(height*scale));

imgView.setImageBitmap(bmap);

imgView.setX(x+((width-bmap.getWidth())/2));
imgView.setY(y+((height-bmap.getHeight())/2));

imgView.setAdjustViewBounds(true);

constraintLayout.addView(imgView);

这给出了以下结果(绿色圆圈为 scale = 1,红色圆圈为 scale = 0.6

enter image description here

有什么想法吗?我真的卡住了。

最佳答案

我假设灰色矩形是普通的 Android Views,它们是 ConstraintLayout 的子项。它们是通过编程方式创建和添加的,因此您必须使用 setId() 方法为它们提供 ID。 ids 必须是正数,并且在此 View 层次结构中必须是唯一的。

要居中的图像的大小并不重要。你只需要给他们适当的约束。

    //Set the id for the greyRectangleLeft
greyRectangleLeft.setId(1)
//Create a new constraint set
ConstraintSet set = new ConstraintSet();

//Clone the current constraints from your ConstraintsLayout to avoid losing them
set.clone(constraintLayout);

//Create the ImageView and set its Bitmap
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bmap);
//The imageView should have an id as well
imageView.setId(2);

//Add the constraints which will center the ImageView within the bounds of the grey_rectangle_left
set.connect(imageView.getId(), ConstraintSet.START, greyRectangleLeft.getId(), ConstraintSet.START);
set.connect(imageView.getId(), ConstraintSet.END, greyRectangleLeft.getId(), ConstraintSet.END);
set.connect(imageView.getId(), ConstraintSet.TOP, greyRectangleLeft.getId(), ConstraintSet.TOP);
set.connect(imageView.getId(), ConstraintSet.BOTTOM, greyRectangleLeft.getId(), ConstraintSet.BOTTOM);

//Set the width and height of your ImageView to the desired width and height
set.constrainWidth(imageView.getId(), bmap.getWidth());
set.constrainHeight(imageView.getId(), bmap.getHeight());

//Add the newly created ImageView to the ConstraintLayout
constraintLayout.addView(imageView);
//Apply the created constraints
set.applyTo(constraintLayout);

greyRectangleRight 和第二个 ImageView 重复(但给它们不同的 ID)。

关于规模,我推荐使用setScaleX()setScaleY()ImageViews

关于android - 在给定矩形边界的情况下以编程方式缩放和居中 imageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48583001/

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