Check for 'nil' when painting a picture in REALbasic

Here is some code for drawing a picture in a window in REAL Studio 2010 using a Canvas object. You may be displaying eye-candy, an advertisement, etc.

Originally I did not include the "IF( p <> nil)". That bit me when I changed the app to dynamically download an image over the net. Of course networks are not reliable. When network failure occurred my image was not loaded. The side-effect of not loading is display of error messages irrelevant to my users. The solution was simple, if the image does not exist (nil) that means it never loaded, so don't bother trying painting a non-existent image.

  // 'Paint' event handler on Canvas object. © 2010 Basil Bourque.
  // This source code may be used freely by anyone taking full responsibility for doing so.

  dim p as Picture = self.adImage

  // Paint image only if it exists. 

  // Non-existent means the image failed to load.
  if( p <> nil) then

    g.drawpicture p,0,0
    // Add a border
    g.forecolor = &cBBBBBB
    g.penheight = 1
    g.penwidth = 1
    g.drawrect (0, 0, p.width, p.height)

  end if

  // fin

No comments:

Post a Comment