Fit Image into PictureBox

前端 未结 9 725
栀梦
栀梦 2020-12-15 14:43
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
    myDatabaseConnection.Open();
    using (SqlCommand SqlComma         


        
9条回答
  •  时光说笑
    2020-12-15 15:41

    The PictureBox.SizeMode options are missing a "fill" or "cover" mode which would be like zoom except with cropping to ensure you're filling the picture box. In CSS it's the "cover" option.

    This code should enable that:

    static public void fillPictureBox(PictureBox pbox, Bitmap bmp)
    {
        pbox.SizeMode = PictureBoxSizeMode.Normal;
        bool source_is_wider = (float)bmp.Width / bmp.Height > (float)pbox.Width / pbox.Height;
    
        var resized = new Bitmap(pbox.Width, pbox.Height);
        var g = Graphics.FromImage(resized);        
        var dest_rect = new Rectangle(0, 0, pbox.Width, pbox.Height);
        Rectangle src_rect;
    
        if (source_is_wider)
        {
            float size_ratio = (float)pbox.Height / bmp.Height;
            int sample_width = (int)(pbox.Width / size_ratio);
            src_rect = new Rectangle((bmp.Width - sample_width) / 2, 0, sample_width, bmp.Height);
        }
        else
        {
            float size_ratio = (float)pbox.Width / bmp.Width;
            int sample_height = (int)(pbox.Height / size_ratio);
            src_rect = new Rectangle(0, (bmp.Height - sample_height) / 2, bmp.Width, sample_height);
        }
    
        g.DrawImage(bmp, dest_rect, src_rect, GraphicsUnit.Pixel);
        g.Dispose();
    
        pbox.Image = resized;
    }
    

提交回复
热议问题