t简介
扩展ImageView。扩展ScaleType属性,和增加srcGravity属性,可设置src显示位置
扩展功能一:扩展ScaleType属性
ScaleType 增加 leftCrop 、 topCrop、rightCrop、bottomCrop
leftCrop : 垂直方向充满,均匀缩放,显示在控件左侧,超出控件部分进行裁剪,优先显示图片左侧内容
topCrop : 水平方向充满,均匀缩放,显示在控件顶部,超出控件部分进行裁剪,优先显示图片顶部内容
rightCrop : 垂直方向充满,均匀缩放,显示在控件右侧,超出控件部分进行裁剪,优先显示图片右侧内容
bottomCrop : 水平方向充满,均匀缩放,显示在控件底部,超出控件部分进行裁剪,优先显示图片底部内容
使用:xml app:scaleType="topCrop" code imageView.setScaleType(ExtendScaleImageView.ExtendScalType.TOP_CROP);
扩展功能二:增加 setGravity()方法,设置src 的显示位置(可以设置上下左右、水平和垂直居中,前提是scaleType设置为 matrix)
使用:xml app:srcGravity="center_horizontal|right" code imageView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
代码实现
package com.ttkx.extendscale;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.HashMap;
import java.util.Map;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
/**
* 扩展ImageView
*
*/
public class ExtendScaleImageView extends AppCompatImageView {
private ExtendScalType mScalType;
private int mGravity = -1;
public ExtendScaleImageView(@NonNull Context context) {
this(context, null);
}
public ExtendScaleImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ExtendScaleImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ExtendScaleType);
final int index = a.getInt(R.styleable.ExtendScaleType_scaleType, -1);
if (index >= 0) {
ExtendScalType scalType = null;
for (Map.Entry<ExtendScalType, ScaleType> entry : ExtendScalType.map.entrySet()) {
if (entry.getKey().nativeInt == index) {
scalType = entry.getKey();
break;
}
}
if (scalType != null) {
setScaleType(scalType);
}
}
final int srcGravity = a.getInt(R.styleable.ExtendScaleType_srcGravity, -1);
setGravity(srcGravity);
a.recycle();