如何在 android 中将 imageView 设置为方形视图?
How to set an imageView to square view in android?
我想创建一个查看 image/poster 的应用程序,我想要正方形的 imageView。在此之前,我尝试获取屏幕宽度并将其分配给图像高度和宽度,像这样
Bitmap newicon = Bitmap.CreateBitmap (int x, int y, int width, int height, matrix, false/true);
但是出现错误"x + width <= bitmap.width()"。这是我目前创建的示例,但我将高度设置为 400dp。我希望高度和宽度灵活取决于 phone 大小。有任何想法吗?
<ImageView
android:src="@android:drawable/ic_menu_gallery"
android:layout_width="match_parent"
android:layout_height="400dp"
android:adjustViewBounds="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:id="@+id/ivPoster" />
你需要为此使用自定义图像视图,看看这个:
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); // Snap to width
}
}
在布局文件中使用它代替 ImageView。
希望对您有所帮助!
我想创建一个查看 image/poster 的应用程序,我想要正方形的 imageView。在此之前,我尝试获取屏幕宽度并将其分配给图像高度和宽度,像这样
Bitmap newicon = Bitmap.CreateBitmap (int x, int y, int width, int height, matrix, false/true);
但是出现错误"x + width <= bitmap.width()"。这是我目前创建的示例,但我将高度设置为 400dp。我希望高度和宽度灵活取决于 phone 大小。有任何想法吗?
<ImageView
android:src="@android:drawable/ic_menu_gallery"
android:layout_width="match_parent"
android:layout_height="400dp"
android:adjustViewBounds="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:id="@+id/ivPoster" />
你需要为此使用自定义图像视图,看看这个:
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); // Snap to width
}
}
在布局文件中使用它代替 ImageView。
希望对您有所帮助!