ImageView CenterCrop效果

package com.example.imageviews;


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;


public class MainActivity extends Activity{
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image=(ImageView) findViewById(R.id.image);

Bitmap bitmaHorizon = BitmapFactory.decodeResource(getResources(),
R.drawable.a);
// 给一个160*240的竖向view,加载一张448*252的横图
// ivVertical.setImageBitmap(resizeBitmap(bitmaHorizon, 160, 240));
image.setImageBitmap(resizeBitmapByCenterCrop(bitmaHorizon, 200, 200));

}

/**
* 以CenterCrop方式resize图片
* @param src  原始图片
* @param destWidth  目标图片宽度
* @param destHeight 目标图片高度
* @return
*/
public Bitmap resizeBitmapByCenterCrop(Bitmap src, int destWidth, int destHeight) {
if (src == null || destWidth == 0 || destHeight == 0) {
return null;
}
// 图片宽度
int w = src.getWidth();
// 图片高度
int h = src.getHeight();
// Imageview宽度
int x = destWidth;
// Imageview高度
int y = destHeight;
// 高宽比之差
int temp = (y / x) - (h / w);
/**
* 判断高宽比例,如果目标高宽比例大于原图,则原图高度不变,宽度为(w1 = (h * x) / y)拉伸
* 画布宽高(w1,h),在原图的((w - w1) / 2, 0)位置进行切割
*/


if (temp > 0) {
// 计算画布宽度
int w1 = (h * x) / y;
// 创建一个指定高宽的图片
Bitmap newb = Bitmap.createBitmap(src, (w - w1) / 2, 0, w1, h);
//原图回收
src.recycle();
return newb;
} else {
/**
* 如果目标高宽比小于原图,则原图宽度不变,高度为(h1 = (y * w) / x),
* 画布宽高(w, h1), 原图切割点(0, (h - h1) / 2)
*/


// 计算画布高度
int h1 = (y * w) / x;
// 创建一个指定高宽的图片
Bitmap newb = Bitmap.createBitmap(src, 0, (h - h1) / 2, w, h1);
//原图回收
src.recycle();
return newb;
}
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值