scaleType分析

 
android的scaleType有center,centerCrop,centerInside,fit,fitCenter,fitStart,fitEnd,Matrix。文章分别分析这接种模式的含义与实现算法。

Center
center不放缩,超出dst显示图片中间的元素,代码中是将canvas的坐标平移到能够将图片显示到屏幕中的位置
     
mDrawMatrix = mMatrix;
mDrawMatrix.setTranslate(Math.round((vwidth - dwidth) * 0.5f),
                         Math.round((vheight - dheight) * 0.5f));

centerCrop
等比例放大图片,保证图片宽高大于等于dst的宽高,一条边等于,一条边大于或者等于。
代码中实际上是对canvas进行缩放,平移。
缩放的比率: 思路就是选择view/drawable的宽或者高占比大的一边的比例进行缩放,这样该边的drawable就会与view一样大,另外一边按照这个比例压缩,值就比view大。
平移的距离: 相等的边不用平移,大的边,需要平移,保证中间显示。
mDrawMatrix = mMatrix;

float scale;
float dx = 0, dy = 0;

if (dwidth * vheight > vwidth * dheight) {
    scale = (float) vheight / (float) dheight;
    dx = (vwidth - dwidth * scale) * 0.5f;
} else {
    scale = (float) vwidth / (float) dwidth;
    dy = (vheight - dheight * scale) * 0.5f;
}

mDrawMatrix.setScale(scale, scale);
mDrawMatrix.postTranslate(Math.round(dx), Math.round(dy));

centerInside
等比例缩小图片,保证图片宽高小于等于dst的宽高
代码中实际上是对canvas进行缩放,平移
缩放的比率: 思路就是如果都小,那么不压缩,否则按照view/drawable的宽或者高小的缩放到view一样大,另外一边由于按照小值进行压缩,值就比view的小
平移的距离: 如果drawable的某个边小与view,平移多出来的长度/2 ,保证居中, 相等的边不用平移
mDrawMatrix = mMatrix;
float scale;
float dx;
float dy;

if (dwidth <= vwidth && dheight <= vheight) {
    scale = 1.0f;
} else {
    scale = Math.min((float) vwidth / (float) dwidth,
            (float) vheight / (float) dheight);
}

dx = Math.round((vwidth - dwidth * scale) * 0.5f);
dy = Math.round((vheight - dheight * scale) * 0.5f);

mDrawMatrix.setScale(scale, scale);
mDrawMatrix.postTranslate(dx, dy);
Fit
实际上对drawable进行缩放


fitcenter
等比例放缩图片,保证图片全部显示在view中且至少有一边等于dst,居中显示
fitStart
等比例放缩图片,保证图片全部显示在view中且至少有一边等于dst,start显示
fitEnd
等比例放缩图片,保证图片全部显示在view中且至少有一边等于dst,end显示
代码中实际上是调用native的方法
缩放的比率:等比例放缩,用小比例值放缩,类似于下面的代码
缩放比例 scale = Math. min(( float) vWidth / ( float) dwidth ,
            ( float) vheight / ( float) dheight) ;


 fitXY
不等比例放缩,保证图片宽高等于dst 
代码中实际上就是设置drawable的bound,保证充满区域
缩放的比率:不等比例放缩,分开计算比值
    /* If the drawable has no intrinsic size, or we're told to
        scaletofit, then we just fill our entire view.
    */
    mDrawable.setBounds(0, 0, vwidth, vheight);
    mDrawMatrix = null;

Matrix
   Scale using the image matrix when drawing



反思:
1.图片组件的缩放实际上是图片已经加载到内存中,通过控制canvas的matrics实现不同的缩放效果,没有改变图片的内存
2.如果不进行放缩,只进行居中平移,那么就是center的效果
3.如果不等比例,就是fitxy,保证宽高相等
4.平移保证位置

总结:
center: 不放缩,居中
centerInsider:等比例小值,居中,都小于就不缩放
centerCrop:等比例大值,居中
fitCenter:等比例小值,居中
fitXY:不等比例

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值