如何让图片完整拉伸显示到自定义六边形PictureBox数组的每个控件中
问题原因
你自定义的六边形形状扩展方法存在坐标系使用错误:Control.Region 属性对应的裁剪区域使用控件自身客户区的相对坐标(原点为控件左上角),但你代码里传入的 x、y 参数是控件在父容器(窗体)上的全局坐标,这就导致生成的六边形裁剪区域大部分落在了控件的可视范围之外,仅剩极小的重叠区域,自然只能显示图片的局部片段甚至单个像素,SizeMode参数也不会生效。
修正后的扩展方法
Option Strict On Imports System.Runtime.CompilerServices Module hexagon <Extension()> Public Sub Shape(ByVal ctrl As Control, ByVal side As Integer) ' 计算六边形边长对应的短边、长边长度 Dim ShortSide As Integer = CInt(System.Math.Sin(30 * System.Math.PI / 180) * side) Dim LongSide As Integer = CInt(System.Math.Cos(30 * System.Math.PI / 180) * side) ' 计算控件客户区内六边形的居中偏移,确保六边形完全落在控件可视范围内 Dim offsetX As Integer = LongSide Dim offsetY As Integer = 0 Dim Points(5) As Point Points(0) = New Point(offsetX, offsetY) Points(1) = New Point(offsetX + LongSide, offsetY + ShortSide) Points(2) = New Point(offsetX + LongSide, offsetY + ShortSide + side) Points(3) = New Point(offsetX, offsetY + ShortSide * 2 + side) Points(4) = New Point(offsetX - LongSide, offsetY + ShortSide + side) Points(5) = New Point(offsetX - LongSide, offsetY + ShortSide) Dim MyPath As New Drawing2D.GraphicsPath MyPath.AddPolygon(Points) MyPath.CloseFigure() ctrl.Region = New Region(MyPath) MyPath.Dispose() ' 自动调整控件尺寸适配六边形大小,避免手动设置尺寸出错 ctrl.Size = New Size(LongSide * 2, ShortSide * 2 + side) End Sub End Module
使用方法
创建PictureBox控件后,直接调用扩展方法即可,无需传入坐标参数,之后正常设置Image和SizeMode属性即可生效:
' 示例:创建边长为50的六边形PictureBox Dim pic As New PictureBox() pic.Shape(50) pic.Image = My.Resources.绵羊图片 ' 替换为你的图片资源 pic.SizeMode = PictureBoxSizeMode.StretchImage ' 或者Zoom均可正常生效 ' 之后设置pic.Location添加到窗体即可
原问题效果参考

内容的提问来源于stack exchange,提问作者Idan Azari
相关产品推荐
相关产品推荐

