在picturebox插入图片,如果图片太小,如何设置图片平铺

在picturebox插入图片,如果图片太小,如何设置图片平铺,第1张

楼主更改Picturebox 的SizeMode试试

zoom 图片的长宽比例会保持不变

atuosize Picturebox的大小会随着图片的大小而更改

ScretchImage 强制使图片的大小跟picturebox的大小相同,图片的长宽比例会发生改变

CenterImage 图片大小不变,图片在picturebox中居中显示,如果图片大小超过picturebox大小,图片会显示不全

将 Picturebox 的 SizeMode 设为atuosize或ScretchImage,但不知这样出的效果能否满足楼主

添加两个Picture控件,先载入Picture2,然后根据Picture1的大小自动调整显示。

代码如下:

Private Sub Form_Load()

    Picture1.AutoRedraw = True '重绘图片

    Picture1.AutoSize = False   '图片框大小不变

    Picture1.Visible = True

    'Picture1.BackColor = RGB(255, 255, 255) '设置图片框背景颜色

    Picture2.AutoSize = True 'Picture2自动缩放以适应图片,不可见

    Picture2.Visible = False

End Sub

Private Sub Command1_Click()

        Picture2.Picture = LoadPicture("C:\2.jpg")          '图片加载到Pic2

        If Picture2.ScaleWidth > Picture2.ScaleHeight Then

            imageWidth = Picture1.ScaleWidth

            imageHeight = Picture1.ScaleHeight * Picture2.ScaleHeight / Picture2.ScaleWidth

        Else

            imageWidth = Picture1.ScaleWidth * Picture2.ScaleWidth / Picture2.ScaleHeight

            imageHeight = Picture1.ScaleHeight

        End If

        Picture1.Cls

        Picture1.PaintPicture Picture2, (Picture1.ScaleWidth - imageWidth) / 2, (Picture1.ScaleHeight - imageHeight) / 2, imageWidth, imageHeight, 0, 0, Picture2.ScaleWidth, Picture2.ScaleHeight

End Sub

效果(由于图片小,于是调整后上下空出来了):

图像没跟着变只有一个原因,SizeMode不为Zoom。

微软有提供现成的方法满足你的需要。你唯一需要知道的是一个Control的Position是相对于其父容器的边缘而言的,它叫ClientPoint坐标,并非屏幕坐标ScreenPoint。

下面是一个小方法,用来将任意Control的位置置于屏幕正中间。

     void SetCenterScreen(Control control)

        {

            int screenWidth = Screen.PrimaryScreen.WorkingArea.Width

            int screenHeight = Screen.PrimaryScreen.WorkingArea.Height

            int targetLocationLeft

            int targetLocationTop

            targetLocationLeft = (screenWidth - control.Width) / 2

            targetLocationTop = (screenHeight - control.Height) / 2

            if (control.Parent != null)

                control.Location = control.Parent.PointToClient(new Point(targetLocationLeft, targetLocationTop))

            else

                control.Location = new Point(targetLocationLeft, targetLocationTop)

        }

 关于缩放的问题。所有的Control都有Scale方法,接受一个SizeF作为比例因子。

所以你的picturebox事件里应该这样写(每次放大到1.1倍):

  pictureBox1.SuspendLayout()

            pictureBox1.Scale(new SizeF { Width = 1.1f, Height = 1.1f })

            SetCenterScreen(pictureBox1)

            pictureBox1.ResumeLayout()

其中,SuspendLayout()是挂起布局引擎,这样会暂时阻止它进行外观和布局上的变更(但是会在自己的Graphics上偷偷画好),直到调用ResumeLayout()时才会一次性的迅速的显示出来。

此外,SizeMode只需要被设置一次,没有必要每次都赋值。

最后补一句,Zoom是“按比例缩放图片”,Strech才是“填满容器”,当然,如果picturebox大小比例和图像宽高比不一致,strech会让图片变形。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11586478.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-17
下一篇2023-05-17

发表评论

登录后才能评论

评论列表(0条)

    保存