我正在开发一个应用程序,用户可以在该应用程序中在屏幕内移动他的图像,然后保存它。
问题是在 Activity 开始时在 ImageView 中定位位图。
这是 XML:
<RelativeLayout
android:id="@+id/image_content_holder"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/top_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:scaleType="matrix"
android:gravity="center|center_vertical"
android:layout_gravity="center|center_vertical"/>
</RelativeLayout>
我正在使用 onTouch 移动 ImageView(好吧,不是 ImageView,而是它的矩阵),它运行良好。
@Override
public boolean onTouch(View v, MotionEvent event)
{
ImageView view = (ImageView) v;
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
mode = DRAG;
start.set((int) event.getX(), (int) event.getY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG)
{
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
}
break;
}
view.setImageMatrix(matrix);
return true;
}
问题 是 Bitmap 在 Activity 开始时的位置。它在上|左而不是中心对齐。像这样:
任何人都可以帮我在 ImageView 中将其居中吗?
最佳答案
如果你想将位图居中对齐,那么你的 ImageView 布局应该是:
<ImageView
android:id="@+id/top_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center"/>
编辑:
如果您需要 scaleType“矩阵”,则使用下一个解决方案:
<ImageView
android:id="@+id/top_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="matrix"
/>
然后在代码中更改图像的偏移量:
final ImageView imageView = (ImageView) findViewById(R.id.top_image);
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= 16) {
imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
Drawable drawable = imageView.getDrawable();
Rect rectDrawable = drawable.getBounds();
float leftOffset = (imageView.getMeasuredWidth() - rectDrawable.width()) / 2f;
float topOffset = (imageView.getMeasuredHeight() - rectDrawable.height()) / 2f;
Matrix matrix = imageView.getImageMatrix();
matrix.postTranslate(leftOffset, topOffset);
imageView.setImageMatrix(matrix);
imageView.invalidate();
}
});
关于ImageView矩阵中的Android中心位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32326573/