none
I have 5 Picture Boxes that use random numbers to locate their position in a small 320,264 area... RRS feed

  • Question

  • I have 5 Picture Boxes that use random numbers to locate their position in a small 320,264 area... The problem is that they overlap each other all the time. I would like to have the picture boxes without overlapping each other. How can I do this?

    Thanks, Neil


    • Edited by vbNeil Thursday, October 17, 2019 4:36 PM Spelling Error
    Thursday, October 17, 2019 4:32 PM

Answers

  • Hi

    Here is one possibile way.

    This is a stand alone example and needs Form1 with Panel1 and PictureBoxes(1-5) of suitable smallish sizeand a Button1. It helps if PB(s) have a contrasting backcolor and/or borderstyle.

    Button will'shuffle'the PB(s) without overlap.

    ' Form1 with 5 pictureboxes (1-5)
    ' and Button1
    
    ' for ease and clarity, set the
    ' PB backcolor(s) and/or BorderStyle(s)
    
    Option Strict On
    Option Explicit On
    Public Class Form1
    	Dim rand As New Random
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		With Panel1
    			.Location = New Point(10, 10)
    			.Size = New Size(320, 264)
    		End With
    	End Sub
    
    	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    		Dim pb As New List(Of Control)
    		For Each c As Control In Panel1.Controls
    			If c.GetType = GetType(PictureBox) Then
    				pb.Add(c)
    			End If
    		Next
    		Dim inter As Boolean = False
    		Dim curr As Integer = -1
    		For pbox As Integer = 0 To pb.Count - 1
    			curr = pbox
    			Do
    				pb(pbox).Location = New Point(rand.Next(1, Panel1.Width - pb(pbox).Width - 2), rand.Next(1, Panel1.Height - pb(pbox).Height - 2))
    				inter = False
    				For i As Integer = 0 To pb.Count - 1
    					If Not i = curr AndAlso pb(i).Bounds.IntersectsWith(pb(pbox).Bounds) Then inter = True
    				Next
    			Loop While inter = True
    		Next
    	End Sub
    End Class


    Regards Les, Livingston, Scotland




    Thursday, October 17, 2019 5:24 PM