2014-10-08 105 views
12

如何从左侧和右侧剪切矩形图像(600 x 300)以适应方形ImageView?我不想调整图片大小,我只是想裁剪,是300×300将图像裁剪为正方形 - Android

[解决方法]

正如@blackbelt说

Bitmap cropImg = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);

是伟大的裁剪图像。那么如何自动裁剪不同尺寸的图像。我创建这个简单的代码为:

// From drawable 
Bitmap src= BitmapFactory.decodeResource(context.getResources(), R.drawable.image); 

// From URL 
Bitmap src = null; 
try { 
    String URL = "http://www.example.com/image.jpg"; 
    InputStream in = new java.net.URL(URL).openStream(); 
    src = BitmapFactory.decodeStream(in); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

int width = src.getWidth(); 
int height = src.getHeight(); 
int crop = (width - height)/2; 
Bitmap cropImg = Bitmap.createBitmap(src, crop, 0, height, height); 

ImageView.setImageBitmap(cropImg); 

回答

3

您可以使用

Bitmap dst = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight); 

从文档:

返回从源 位图的指定子集的不可变位。新的位图可能与源相同,或者可能有复制品 。它使用与原始位图相同的密度进行初始化。

Here你可以找到的文档

16

扩大一点上回答上述

由于在某些情况下,你可以用例外最终没有预期结果,只是通过使用Bitmap.createBitmap(),就像下面这样:

java.lang.IllegalArgumentException异常:X +宽度必须< = bitmap.width()

赫雷什是一个小的函数,它的作物和处理的某些情况下,公共。

编辑:根据droidster的说法更新。

public static Bitmap cropToSquare(Bitmap bitmap){ 
    int width = bitmap.getWidth(); 
    int height = bitmap.getHeight(); 
    int newWidth = (height > width) ? width : height; 
    int newHeight = (height > width)? height - (height - width) : height; 
    int cropW = (width - height)/2; 
    cropW = (cropW < 0)? 0: cropW; 
    int cropH = (height - width)/2; 
    cropH = (cropH < 0)? 0: cropH; 
    Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight); 

    return cropImg; 
} 

我做了几个不同分辨率和大小的图像测试,它按预期工作。

它也可以在其他情况下使用,例如当您试图制作一个“完美”圆形图像并需要传递方形位图等时

+1

这正是我一直在寻找,获得完美的圆形图像,而不是椭圆形。但是,如果图像的高度大于宽度,则不会在中心裁剪,因为在createBitmap方法中y参数的值为0。这是如何解决的:添加这两行:'int cropH =(height - width)/ 2; \t cropH =(cropH <0)? 0:cropH;'使用cropH作为y值。 \t'位图cropImg = Bitmap.createBitmap(位图,cropW,cropH,newWidth,newHeight);' – 2015-03-14 14:12:52

+0

不错,我看到你的观点....基本上要对宽度和高度进行相同的计算。 – 2015-04-18 20:49:22

1

组固定图像视图的高度,宽度,并设置两个属性,以图像视图

android:adjustViewBounds="true" 
android:scaleType="centerCrop"