ImageView ScaleType扩展

t简介

扩展ImageView。扩展ScaleType属性,和增加srcGravity属性,可设置src显示位置

 扩展功能一:扩展ScaleType属性

 ScaleType 增加 leftCrop topCroprightCropbottomCrop

 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();
   
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值