Android基础控件——ImageView的自定义,巧用Matrix实现图片不变形的炫酷PK条

前言

在开发中常常会遇到PK条制作,如果在PK条中是纯色的情况下,比较好办,如下:

《Android基础控件——ImageView的自定义,巧用Matrix实现图片不变形的炫酷PK条》

我们通常会设置其权重进行更新两个PK条的进度,实现起来也简单

//更新PkBar宽度比例
private void updateLayoutParams(float ratio) {
    LinearLayout.LayoutParams paramsLeft = (LinearLayout.LayoutParams) mLeftBar.getLayoutParams();
    LinearLayout.LayoutParams paramsRight = (LinearLayout.LayoutParams) mRightBar.getLayoutParams();
    paramsLeft.weight = ratio;
    paramsRight.weight = 1 - ratio;
    mLeftBar.setLayoutParams(paramsLeft);
    mRightBar.setLayoutParams(paramsRight);
}

如果是在纯色的基础上,采用酷炫的图片进行遮盖,这样的话,可能会导致素材的压缩情况,如下:

《Android基础控件——ImageView的自定义,巧用Matrix实现图片不变形的炫酷PK条》

通过素材的对比,明显看到是有压缩的

《Android基础控件——ImageView的自定义,巧用Matrix实现图片不变形的炫酷PK条》

《Android基础控件——ImageView的自定义,巧用Matrix实现图片不变形的炫酷PK条》

我们可以通过自定义
ImageView
ScaleType,通过裁剪达到我们的效果

《Android基础控件——ImageView的自定义,巧用Matrix实现图片不变形的炫酷PK条》

实现

1、搭建ImageView

通过上面看到,我们会用两边都是ImageView去填充,通过设置不用的权重进行PK进度的更新,为了兼容我们提供四种方向的缩放裁剪模式,而且继承AppCompatImageView

public class CropImageView extends AppCompatImageView {

    private CropType mCropType;
    private Bitmap mBitmap;

    //提供四种方向的缩放裁剪模式
    public enum CropType {
        LEFT_CROP,
        RIGHT_CROP,
        TOP_CROP,
        BOTTOM_CROP
    }

    public CropImageView(Context context) {
        this(context, null);
    }

    public CropImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CropImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initTypeArray(context, attrs);
        initView();
    }
}

2、获取在xml的属性

在styleable中声明我们需要的裁剪模式

<!--CropImageView 裁剪缩放模式-->
<declare-styleable name="CropImageView">
    <attr name="cropType">
        <enum name="leftCrop" value="0" />
        <enum name="rightCrop" value="1" />
        <enum name="topCrop" value="2" />
        <enum name="bottomCrop" value="3" />
    </attr>
</declare-styleable>

接着代码就是常规的获取自定义属性

private void initTypeArray(Context context, AttributeSet attrs) {
    final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CropImageView);
    int cropType = typedArray.getInt(R.styleable.CropImageView_cropType, -1);
    if (cropType == 0) {
        mCropType = CropType.LEFT_CROP;
    } else if (cropType == 1) {
        mCropType = CropType.RIGHT_CROP;
    } else if (cropType == 2) {
        mCropType = CropType.TOP_CROP;
    } else if (cropType == 3) {
        mCropType = CropType.BOTTOM_CROP;
    }
    typedArray.recycle();
}

3、裁剪ImageView

这里是最重要的一步,通过阅读ImageView的源码,模仿ScaleType对Matrix进行操作达到我们想要的效果

    if (mCropType != null) {
        updateCropMatrix();
    }
}

private void updateCropMatrix() {
    //如果没有炫酷PK条就默认设置个缩放模式
    if (mBitmap == null) {
        if (getScaleType() == ScaleType.MATRIX) {
            setScaleType(ScaleType.CENTER_CROP);
        }
        return;
    }
    //真正处理炫酷PK条
    setScaleType(ScaleType.MATRIX);
    Matrix mMatrix = new Matrix();
    float scale = 1; //缩放图片大小比例
    float dx = 0, dy = 0;
    final int vHeight = getHeight() - getPaddingLeft() - getPaddingRight();//获取真实高度
    final int vWidth = getWidth() - getPaddingTop() - getPaddingBottom();//获取真实宽度
    final int dWidth = mBitmap.getWidth();
    final int dHeight = mBitmap.getHeight();

    if (mCropType == CropType.LEFT_CROP) {
        scale = (float) vHeight / (float) dHeight;
        dx = 0;
    } else if (mCropType == CropType.RIGHT_CROP) {
        scale = (float) vHeight / (float) dHeight;
        dx = vWidth - dWidth * scale; //x方向平移,显示图片右边区域内容
    } else if (mCropType == CropType.TOP_CROP) {
        scale = (float) vWidth / (float) dWidth;
        dy = 0;
    } else if (mCropType == CropType.BOTTOM_CROP) {
        scale = (float) vWidth / (float) dWidth;
        dy = vHeight - dHeight * scale; //y方向平移,显示图片底边区域内容
    }
    mMatrix.setScale(scale, scale); //先将图片宽(或高)缩放到View的同等大小
    mMatrix.postTranslate(Math.round(dx), Math.round(dy));
    setImageMatrix(mMatrix);
}

在真正的操作上,你可以理解为CropImageView就是一个View去承载一张Bitmap,由于我们的CropImageView大小是固定不变的,而承载的Bitmap是可以通过缩放等功能进行处理的,通过移动和缩放Bitmap的大小,如果Bitmap的大小大于原先的CropImageView的大小,这样不知不觉之中就形成了Bitmap的裁剪功能

  • Bitmap:包含照片的所有像素信息、宽高等其他信息
  • Matrix:Matrix的本质是矩阵,通过矩阵的计算可以进行图片的旋转、缩放等功能

通过计算炫酷PK条的宽高是否要适配原先ImageView的大小,进行缩放动作,由于缩放的动作是在CropImageView本身的左上角实现的,我们需要对CropImageView和Bitmap左上角或者右上角的对齐,这样Bitmap才刚好完整的盖在CropImageView上

  • LEFT_CROP:左上角需要对其,本身就是在左上角进行缩放的,所以不需要平移
  • RIGHT_CROP:右上角需要对其,所以通过计算CropImageView和Bitmap的宽度差,进行平移
  • TOP_CROP:左上角需要对其,本身就是在左上角进行缩放的,所以不需要平移
  • BOTTOM_CROP:左下角需要对其,所以通过计算CropImageView和Bitmap的高度差,进行平移

适配

通过提供接口的形式让外部调用,在每次设置变化的时候都会去进行重新计算,在onSizeChanged的时候也需要重新计算,这是考虑到父View的大小可能会被外部改变

public void setCropType(CropType cropType) {
    mCropType = cropType;
    updateCropMatrix();
}

@Override
public void setImageBitmap(Bitmap bm) {
    super.setImageBitmap(bm);
    mBitmap = bm;
    updateCropMatrix();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    updateCropMatrix();
}

使用

1、xml

在xml上配置好最原始的图片背景色

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cropImg="http://schemas.android.com/apk/res-auto"
    android:id="@+id/ll_pk_bar_bg"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_margin="16dp"
    android:layout_centerVertical="true"
    android:orientation="horizontal">

    <com.example.customimage.CropImageView
        android:id="@+id/img_left_bar"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#0caafc"
        cropImg:cropType="leftCrop" />

    <com.example.customimage.CropImageView
        android:id="@+id/img_right_bar"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#f2a603"
        cropImg:cropType="rightCrop" />
</LinearLayout>

2、代码

代码上去设置我们的炫酷PK条,通过权重去更新进度

public class MainActivity extends AppCompatActivity {

    private CropImageView mLeftBar;
    private CropImageView mRightBar;

    private float ratio = 0.0f;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ratio += 0.1f;
            updateLayoutParams(ratio);
            if (ratio <= 1.0f) {
                mHandler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BitmapDrawable leftDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.left_bar);
        Bitmap leftBitmap = leftDrawable.getBitmap();
        BitmapDrawable rightDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.right_bar);
        Bitmap rightBitmap = rightDrawable.getBitmap();

        mLeftBar = findViewById(R.id.img_left_bar);
        mRightBar = findViewById(R.id.img_right_bar);

        mLeftBar.setImageBitmap(leftBitmap);
        mRightBar.setImageBitmap(rightBitmap);

        mHandler.sendEmptyMessageDelayed(0, 1000);
    }

    //更新PkBar宽度比例
    private void updateLayoutParams(float ratio) {
        LinearLayout.LayoutParams paramsLeft = (LinearLayout.LayoutParams) mLeftBar.getLayoutParams();
        LinearLayout.LayoutParams paramsRight = (LinearLayout.LayoutParams) mRightBar.getLayoutParams();
        paramsLeft.weight = ratio;
        paramsRight.weight = 1 - ratio;
        mLeftBar.setLayoutParams(paramsLeft);
        mRightBar.setLayoutParams(paramsRight);
    }
}
    原文作者:Android架构木木
    原文地址: https://www.jianshu.com/p/fb97b4f91fff
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞