将位图图像裁剪为自定义正方形

Posted

技术标签:

【中文标题】将位图图像裁剪为自定义正方形【英文标题】:Crop Bitmap image to custom sguare 【发布时间】:2017-10-24 20:24:21 【问题描述】:

Image sample 我有这个方法来裁剪我的图像,但是高度尺寸在裁剪上不起作用,只有重量是正确的。我找不到问题。我想使用我的屏幕宽度和高度作为动态宽度和高度。

public Bitmap cropToSquare(Bitmap bitmap)
        int width  = mScreenWidth ;
        int height = mScreenHeight;
        int newWidth = width - 2 * 10;
        int newHeight = (height- newWidth) / 2;

        Bitmap cropImg = Bitmap.createBitmap(bitmap, 0, 0, newWidth, newHeight);
        return cropImg; 

    

【问题讨论】:

请说明你想通过附上快照实现什么;这将有助于我们更好地理解问题!!!!!! 【参考方案1】:

这是我的解决方案:

public static Bitmap getResizedClippedBitmap (Bitmap bm, int newWidth, int newHeight) 

    Bitmap targetBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(targetBitmap);

    float originalWidth = bm.getWidth();
    float originalHeight = bm.getHeight();

    float scale, xTranslation = 0.0f, yTranslation = 0.0f;
    if (originalWidth > originalHeight) 
        scale = newHeight/originalHeight;
        xTranslation = (newWidth - originalWidth * scale)/2.0f;
    
    else 
        scale = newWidth / originalWidth;
        yTranslation = (newHeight - originalHeight * scale)/2.0f;
    

    Matrix transformation = new Matrix();
    transformation.postTranslate(xTranslation, yTranslation);
    transformation.preScale(scale, scale);

    Paint paint = new Paint();
    paint.setFilterBitmap(true);
    canvas.drawBitmap(bm, transformation, paint);

    return targetBitmap;

您可以在此处找到其他一些实用程序:BitmapUtils.java 希望对您有所帮助。

【讨论】:

以上是关于将位图图像裁剪为自定义正方形的主要内容,如果未能解决你的问题,请参考以下文章

如何从顶部和底部裁剪位图图像?

将位图裁剪为特定的宽度和高度,而不会丢失分辨率

Android:从位图裁剪位图并设置为 ImageView src

以矩形裁剪位图图像

将位图设置为背景并裁剪它

如何裁剪位图并获得图像的下 50%