我的问题
假设我有一个位图 - 将其称为 bmap
,尺寸为 100x75
(bmap.getWidth() x bmap.getHeight()
)
假设我有一个矩形 rect
,位于手机屏幕上的某个点 (x,y),尺寸为 500x350
(width x height
)
我如何编写一段代码,使这个位图在边界矩形内居中。
注意:因为我使用的是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
有什么想法吗?我真的被困住了。
我假设灰色矩形是普通的 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/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://www.ogeek.cn/) | Powered by Discuz! X3.4 |