图片自动裁剪,边框问题

Image auto-cropping, issue with borders

我在我的应用程序中谈论照片。在我拍摄之后,在布局的下一个屏幕上,我希望它像图像一样自动裁剪。 但是我经常丢失照片的边界并且我有奇怪的边界(在图像中用红色表示)。

这是我的代码:

Android code 
private void NewElement_OnDrawBitmap(object sender, EventArgs e)
        {
            if (this.ViewGroup != null)
            {
                //get the subview
                Android.Views.View subView = ViewGroup.GetChildAt(0);
                int width = subView.Width;
                int height = subView.Height;

                //create and draw the bitmap
                Bitmap b = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
                Canvas c = new Canvas(b);
                ViewGroup.Draw(c);

                //save the bitmap to file
                bytes = SaveBitmapToFile(b);
            }
        }


iOS code
 UIGraphics.BeginImageContextWithOptions(this.Bounds.Size, true, 0);
            this.Layer.RenderInContext(UIGraphics.GetCurrentContext());
            var img = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();
            using (NSData imageData = img.AsPNG())
            {
                bytes = new Byte[imageData.Length];
                System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
            }
        private byte[] SaveBitmapToFile(Bitmap bm)
        {
            MemoryStream ms = new MemoryStream();
            bm.Compress(Bitmap.CompressFormat.Png, 100, ms);
            return ms.ToArray();
        }
}

从您的共享代码来看,您没有进行任何裁剪,因此您的应用只是将您的原始图片放入视图中,而您提到的边框可能是您视图的背景。 还有你的项目代码,我看到你加了

Bitmap bitmap = Bitmap.CreateBitmap(b, 0, 0, (98 * width) / 100, (82 * height) / 100);  

是的,这是裁剪图片,但这只是将图像从 top-left 角裁剪为 98% 宽度和 82% 高度。很像

如果您想将图片裁剪成一个居中的正方形,您可以简单地:

int offset = (height - width) / 2;
Bitmap bitmap = Bitmap.CreateBitmap(b, 0, offset, width, height- offset);

但是如果你想对图像做更多的操作,比如 move/zoom...然后裁剪,我建议你转向现有的解决方案,比如 FFImageLoading or Syncfusion。或者您必须计算所有 move/zoom 数据才能进行裁剪。