Tuesday, September 3, 2013

Grabbing pixels, magnifying window

With the developer tools of Apple, in the Graphic Tools, there is a small program that magnifies a small area of the screen. This can be handy to see what is happening on the pixel-level with your program as well as for pixel-perfect aligning of any graphics you are drawing in your application.

This little tool 'Pixie' runs of course in OSX. Apart from curiosity - could we do this with RealBasic - we also rather wanted this function on some older systems running OS9.

And indeed we can do this with RealBasic.


The code in the method listed below does this by doggedly asking for the color of a System.Pixel at a coordinate on the screen. With the color of the pixel of the screen then a small rectangle is drawn onto the receiving canvas to create a magnified view.


  Sub UpdateImage(Cnv As Canvas)

  Dim mX, mY As Integer // the mouse position in global coords
  Dim nX, nY As Integer // the size of the sample we are magnifying
  Dim dX, dY As Integer // the mid-point of the magnifying area
  Dim CounterX, CounterY As Integer
  Dim mag As Integer // magnification factor
  
  mag = App.MagFactor  // get from preferences 
  
  mX = System.MouseX
  mY = System.MouseY
  
  // if the pref is to only update when the mouse moved, 
  // check for the condition and bail from Sub if so 
  If App.LiveUpdating = False Then
    If mX = LastX And mY = LastY Then 
      Exit // bail
    End if
  End If
  
  // still here, so need to update our image so store the current coords
  LastX = mX
  LastY = mY
  
  
  // determine the size of the sample we need to take from Screen by
  // dividing the target canvas size by the magnification factor
  nX = Floor( Cnv.Width / mag )
  nY = Floor( Cnv.Height / mag )
  
  // then the midpoint we need to sample around
  dX = Round( nX/2 )
  dY = Round( nY/2)
  
  // then sample the color of every pixel we need to magnify and draw
  // a corresponding square onto the canvas (that was passed as param)
  For CounterX = 0 To nX
    For CounterY = 0 To nY
      magPic.Graphics.ForeColor = System.Pixel(mX+CounterX-dX, mY+CounterY-dY)
      magPic.Graphics.FillRect( CounterX*mag, CounterY*mag,mag,mag)
    Next
  Next
  
  Cnv.Refresh

  End Sub

This method is used to make a magnifying window very much like the Pixie tool. The program in this source is localized into Dutch, but we're sure you will be able to figure out what it all means and be able to change it to the language of your choice. Source is provided right here.

The source also includes handling of preferences and remembering window positions. Because it is not possible to change the type of a Window (document, floating) after it has been created, the program uses two windows and shows/hides these depending on the program state.

Activating the program with a mouse click in the system-wide floater also is a bit of a hack. Have a look at the code :)