0m4*_*m4r 5 android drawable imageview
我正在尝试实现一个可以同时保存横向或纵向图像的ImageView.这些图像应该适合图像视图的宽度(如果是横向)或高度(如果是肖像),但无论如何它们必须与视图的顶部对齐,没有边距或填充.
我想实现的是一样的东西android:scaleType="fitStart",但集中在人像图像的情况下,或对准景观图像的情况下到上.
添加:
现在我正在使用这样一个丑陋的代码,这似乎有效,但不确定它是最好的解决方案:
<com.custom.layout.MyImageView
android:id="@+id/detail_view_image"
android:src="@drawable/logo"
android:background="#fff"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:cropToPadding="false"
android:adjustViewBounds="false"
/>
Run Code Online (Sandbox Code Playgroud)
然后在我的课上,我扩展了ImageView:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int imgWidth = getDrawable().getIntrinsicWidth();
int imgHeight = getDrawable().getIntrinsicHeight();
if(imgWidth>imgHeight)
setScaleType(ScaleType.FIT_START);
else
setScaleType(ScaleType.FIT_CENTER);
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(width, height);
}
Run Code Online (Sandbox Code Playgroud)
您可以在 onCreate() 方法中放置一个片段,根据手机的方向更改 ImageView 的scaleType,而不是覆盖本机视图。
onCreate 方法中的一些示例片段(我不确定它是否像那样工作,但为了了解这个想法):
ImageView imgView = findViewById(R.id.myImage);
//portrairt orientation
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
imgView.setScaleType(ScaleType.FIT_CENTER);
} else { //landscape orientation
imgView.setScaleType(ScaleType.FIT_START);
}
Run Code Online (Sandbox Code Playgroud)
因此,当方向发生变化时,将再次调用 onCreate 并更改视图的比例类型,如果您要重写 onConfigurationChanged() 那么您应该在任何您想要的地方再次添加上面的代码片段。尝试一下并告诉我是否有效