vb13

10
Fading A Bitmap / PictureBox This short bit of code shows how to fade a picture inside a PictureBox using a few simple WinAPI methods. The code works by creating a memory compatible DC and Bitmap to that of the picture within the PictureBox. The PictureBox is then cleared and has it's background set to various shades of gray (eventually black) - t he bitmap is then 'blitted' to the P ictureBox and each pixel is 'AND'ed with the background colour to achieve the fade effect. ' ' Form1 with a PictureBox (picture1) and a command button (command1) ' ' private Declare Function BitBlt Lib "gdi32" ( byval hDestDC as Long, _  byval x as Long, byval y as Long, byval nWidth as Long, _  byval nHeight as Long, byval hSrcDC as Long, byval xSrc as Long, _  byval ySrc as Long, byval dwRop as Long) as Long private Declare Function CreateCompatibleDC Lib "gdi32" _ (byval hdc as Long) as Long private Declare Function CreateCompatibleBitmap Lib "gdi32" _ (byval hdc as Long, byval nWidth as Long, byval nHeight as Long) as Long private Declare Function DeleteDC Lib "gdi32" ( byval hdc as Long) as Long private Declare Function DeleteObject Lib "gdi32" _ (byval hObject as Long) as Long private Declare Function SelectObject Lib "gdi32" ( byval hdc as Long, _  byval hObject as Long) as Long ' private Declare Sub Sleep Lib "kernel32" ( byval dwMilliseconds as Long) ' private Const SRCAND = &H8800C6 private Const SRCCOPY = &HCC0020 ' private Sub Command1_Click() Dim lDC as Long Dim lBMP as Long Dim W as Integer Dim H as Integer Dim lColor as Long ' Screen.MousePointer = vbHourglass ' W = ScaleX(Picture1.Picture.Width, vbHimetric, vbPixels) H = ScaleY(Picture1.Picture.Height, vbHimetric, vbPixels)  '  ' Create Memory Compatible Bitmap to that in Picture1  ' lBMP = CreateCompatibleBitmap(Picture1.hdc, W, H) No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

Upload: vijini-pathiraja

Post on 10-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 1/10

Fading A Bitmap / PictureBox

This short bit of code shows how to fade a picture inside a PictureBoxusing a few simple WinAPI methods.

The code works by creating a memory compatible DC and Bitmap to thatof the picture within the PictureBox. The PictureBox is then cleared andhas it's background set to various shades of gray (eventually black) - thebitmap is then 'blitted' to the PictureBox and each pixel is 'AND'ed withthe background colour to achieve the fade effect.

'' Form1 with a PictureBox (picture1) and a command button (command1)

''private Declare Function BitBlt Lib "gdi32" (byval hDestDC as Long, _  byval x as Long, byval y as Long, byval nWidth as Long, _  byval nHeight as Long, byval hSrcDC as Long, byval xSrc as Long, _  byval ySrc as Long, byval dwRop as Long) as Longprivate Declare Function CreateCompatibleDC Lib "gdi32" _

(byval hdc as Long) as Longprivate Declare Function CreateCompatibleBitmap Lib "gdi32" _

(byval hdc as Long, byval nWidth as Long, byval nHeight as Long) as Longprivate Declare Function DeleteDC Lib "gdi32" (byval hdc as Long) as Longprivate Declare Function DeleteObject Lib "gdi32" _

(byval hObject as Long) as Long

private Declare Function SelectObject Lib "gdi32" (byval hdc as Long, _  byval hObject as Long) as Long'private Declare Sub Sleep Lib "kernel32" (byval dwMilliseconds as Long)'private Const SRCAND = &H8800C6private Const SRCCOPY = &HCC0020'private Sub Command1_Click()

Dim lDC as LongDim lBMP as LongDim W as IntegerDim H as Integer

Dim lColor as Long'Screen.MousePointer = vbHourglass

'W = ScaleX(Picture1.Picture.Width, vbHimetric, vbPixels)H = ScaleY(Picture1.Picture.Height, vbHimetric, vbPixels)

  '  ' Create Memory Compatible Bitmap to that in Picture1  '

lBMP = CreateCompatibleBitmap(Picture1.hdc, W, H)

icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 2/10

  '  ' Create Compatible DC in memory  '

lDC = CreateCompatibleDC(Picture1.hdc)  '  ' Select the Bitmap into the memory DC  '

Call SelectObject(lDC, lBMP)BitBlt lDC, 0, 0, W, H, Picture1.hdc, 0, 0, SRCCOPY

  '  ' Quickly clear the Picture in Picture1  '

Picture1 = LoadPicture("")

  for lColor = 255 to 0 step -3  '  ' set the backcolor to a gray scale -> black   '

Picture1.BackColor = RGB(lColor, lColor, lColor)  '

  ' Copy the bitmap into the picturebox 'AND' with the backcolor  '

BitBlt Picture1.hdc, 0, 0, W, H, lDC, 0, 0, SRCAND  '  ' Pause for a bit  '

Sleep 15  next  '  ' Clear up our DC's and Bitmaps  '

Call DeleteDC(lDC)Call DeleteObject(lBMP)

Screen.MousePointer = vbDefault'End Sub'

A method to get the pixel color under the mouse pointer

Author: Aaron YoungAuthor's WebSite: http://www.pressenter.com/~ajyoung

This small code sample shows how to obtain the RGB color of any pixel

under the cursor.

The code uses a timer control to fire events ever 100'th of a second andthen uses the GetPixel , GetCursorPos , and GetDC WinAPI calls toobtain the value.

icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 3/10

option Explicit'''Aaron Young'Analyst Programmer'[email protected] <mailto:[email protected]>'http://www.pressenter.com/~ajyoung'

'Add a Timer Control to a Form, then use this code And point to anywhere on your screento have'the RGB value appear In the Forms Caption.'private Type POINTAPI

x as Longy as Long

End Type'private Declare Function GetPixel Lib "gdi32" (byval hdc as Long, _  byval x as Long, byval y as Long) as Long

private Declare Function GetCursorPos Lib "user32" (lpPoint as POINTAPI) as Longprivate Declare Function GetWindowDC Lib "user32" (byval hwnd as Long) as Long'private Sub Form_Load()

Timer1.Interval = 100End Sub'private Sub Timer1_Timer()

Dim tPOS as POINTAPIDim sTmp as stringDim lColor as LongDim lDC as Long

'

lDC = GetWindowDC(0)Call GetCursorPos(tPOS)lColor = GetPixel(lDC, tPOS.x, tPOS.y)Label2.BackColor = lColor

'sTmp = Right$("000000" & Hex(lColor), 6)Caption = "R:" & Right$(sTmp, 2) & " G:" & mid$(sTmp, 3, 2) & " B:" &

Left$(sTmp, 2)End Sub'

An Introduction To Object Orientated Programming

with VB4/5/6

Author: Chris EastwoodAuthor's WebSite: http://www.vbcodelibrary.com

Introduction

icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 4/10

This is the first in a series of Object Orientated Programming (OOP)tutorials using Visual Basic. This first part introduces you to the conceptsbehind OOP and explains objects as they are used in Visual Basic.

Definition of an Object

It seems that there is no one definition of an object that developers anddesigners can agree on. Possibly the one that is nearest to the mark is :"An object is an entity able to save a state (information) and which offers

a number of operations (behaviour) to either examine or affect this state"

(From Jacobson: Object Orientated Software Engineering)That's all very well, but what does that mean to a VB Programmer ? If you've ever written a Visual Basic program with a form or controls, thenyou've already had a quick taste of objects. Consider a Visual Basic Form- a form is an object that VB knows about. Once a form is running in yourprogram, it is able to :

• Save a State (eg. Height, Width, Caption etc)

•  Offer a number of operations (eg. Show, Hide, etc)

An object is supposed to offer a programmer or another program, anApplication Programming Interface (API). For an object, this consists of :

•  Properties - the ability to set and get 'state' values referenced by theobject (eg. Form1.Height etc)

•  Methods - the routines available from the object that allow somekind of processing to take place within the object (eg.Form1.Show, Form1.Hide etc)

Definition of a Class Module

A class module is simply a description or a 'blueprint' of an Object. Forexample :

•  My telephone call to my mechanic on 20th February 2000

•  My telephone call to a scrapyard on 21st February 2000

- These could both be called Instances of the class Telephone Call

Remember

An object is an instance of a class - whereas a class is a type of whichthere maybe many instances of objects

Thinking about objects

Let's consider how we can perceive a real-world object.When I get into my car in the morning to drive to work, I place my key inthe ignition to start the engine and (hopefully) drive to work carefree. I

icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 5/10

don't need to know about the internal combustion engine to drive my car,nor do I need to understand how the wiring works in order to operate mylights and indicators. The car can be said to provide an Interface that Ineed to know about (and a separate interface for those brave enough tolook under the bonnet). My car can be though of as an object that offers

properties (current speed, fuel level, oil level etc) and methods (start-engine, stop engine etc).

Signs of a 'good' Object

A class representing an object should :

•  Provide a well-defined API - this should provide external software / programmers with the ability to perform valid operations with theobject.

•  Be as complete as possible - the programmer shouldn't have to callexternal routines in order to 'do something' with the object

•  Be Robust - a class should reject illegal or incorrect input. Forinstance, my 'car' object shouldn't allow me to try and change intosixth gear, nor should it allow me to us the 'driving' method beforethe 'start-engine' method has been called

Real World VB Object Programming

Now that you have a better understanding of the concepts behind ObjectOrientated Programming, let's move onto a Visual Basic example. Since

VB4, developers have been able to add class modules to their projects.While a lot of people assume that just adding a class to your programmakes it Object Orientated, the program is doomed to failure unless thereis a good design for the system.

A good design comes from a good understanding of the problem / projectdomain - you need to fully understand :

•  What are the objects in the system

•  What are the relationships between the objects

•  What are the interactions between the objectsFor our VB example, we'll take a 'Bank Account' real world object andcreate a Visual Basic class that models it's real-world behaviour.When we think about a Bank Account, we think of it as having :

•  A Balance

•  An Interest Rate

icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 6/10

•  A monthly Fee

•  A customer

•  The ability to accept a deposit of funds

•  The ability to allow a withdrawl of funds

•  The ability to calculate interest

Hopefully, you'll have read through the above list and already identifiedwhat are the properties and methods of the class module we are about tocreate. Let's jump straight into the Visual Basic IDE and start creating ourproject.Create a standard VB EXE project, call it prjBankAccount1 . Next, add aclass module to the project and call it cBankAccount .The cBankAccount class is listed below - notice how when the'cBankAccount' object is instantiated (ie. Set o = New cBankAccount), the

class uses it's own internal properties to set the internal varables. Thisensures that errors are caught right from the start.

option Explicit'' Bank Account Class'private mdblBalance as Doubleprivate mdblInterestRate as Doubleprivate mdblMonthlyFee as Double'private Sub Class_Initialize()'

' Class Initialize is the first routine' called when you create a 'cBankAccount'' object.'' Eg. set oBA = new cBankAccount'

mdblBalance = 0  me.InterestRate = 1.75  me.MonthlyFee = 5'End Sub'private Sub Class_Terminate()'' Class_Terminate is called when you' set the object to nothing (or it falls out of scope)'End Sub'public property get Balance() as Double'' Return the Balance of this account'

icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 7/10

Balance = mdblBalance'End property'public property get InterestRate() as Double'' Return the interest rate'

InterestRate = mdblInterestRate'End property'public property let InterestRate(byval dblNewInterestRate as Double)'' Check for invalid interest rates'

If dblNewInterestRate < 0 thenErr.Raise vbObjectError + 2001, _

"cBankAccount::InterestRate", _"Invalid Interest Rate set : " & dblNewInterestRate

End If '' Now set the rate'

mdblInterestRate = dblNewInterestRateEnd property'public property let MonthlyFee(byval dblNewFee as Double)'' Check for invalid Fee'

If dblNewFee < 0 thenErr.Raise vbObjectError + 2003, _

"cBankAccount::MonthlyFee", _"Invalid Fee Amount : " & dblNewFee

End If '

mdblMonthlyFee = dblNewFee'End property'public Sub MonthlyProcessing()'' This routine takes the monthly fee' from the account, then updates the' balance with interest earned.

' CalcFeeCalcInterest

'End Sub'public Sub Withdraw(byval dblAmount as Double)'' Withdraw some money from the account'

icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 8/10

' Sanity check first !'

If dblAmount <= 0 thenErr.Raise vbObjectError + 2002, _

"cBankAccount::Withdraw", _"Invalid Withdraw amount : " & dblAmount

End If 

If (mdblBalance - dblAmount) < 0 thenErr.Raise vbObjectError + 2003, _

"cBankAccount::Withdraw", "Insufficient Funds"End If 

mdblBalance = mdblBalance - dblAmountEnd Sub'public Sub Deposit(byval dblAmount as Double)'' Deposit some money to the account'

' Sanity check first'

If dblAmount <= 0 thenErr.Raise vbObjectError + 2002, _

"cBankAccount::Deposit", _"Invalid deposit amount : " & dblAmount

End If '

mdblBalance = mdblBalance + dblAmount'End Sub'private Sub CalcFee()

'' This routine removes the monthly fee' from the balance'

mdblBalance = mdblBalance - mdblMonthlyFee'End Sub'private Sub CalcInterest()'' This is private, as we don't want' other programs / programmers updating' the balance except through the

' proper interfaces'' The calculation updates the balance with the monthly interest' due'

mdblBalance = mdblBalance + _(mdblBalance * (mdblInterestRate / 120))

'End Sub

icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 9/10

''

The class module will be expanded upon in the next part of thistutorial when we'll cover another object orientated concept -polymorphism.

Optimizing Tip on Adaptive Arithmetic Coding

This article was contributed by Alexey V. Shanin, Russia.The arithmetic coding data compression method is very well-known. It has a number of implementations used in of popular complex, multistaged compression techniques. Thisarticle, therefore, assumes that the reader will be readers with the basic concepts of arithmetic coding.This article describes an optimization point I found in the most commonly used adaptiveWitten-Neal-Cleary implementation (also known as "the finite-precision algorithm"). Fordetails (including source code samples), you can refer to the Mark Nelson's article on

arithmetic coding. Below I'm using the common terminology that article also follows.In the practical implementations I've seen, the cumulative symbol frequency table (acomponent of the algorithm) was represented by an array of integer numbers containing,for each given symbol, the sum of frequencies of all the symbols having indices less thangiven. The array was sorted in arbitrary fashion (for instance, by "values" of symbols) orby (non-cumulative) frequencies of symbols. Encoding a regular symbol needscorresponding frequency interval to be determined; decoding needs determining afrequency interval containing a given point. Both actions are followed by updating theadaptive model, what's commonly done by increasing the non-cumulative symbol'sfrequency (= increasing the cumulative frequencies of all the symbols having indices notless than the one of the symbol encoded/decoded). The first thing is fast, the second can

be done fast enough by binary search in the array (which is monotone; I've noted it's notdone in the sample I've referenced above), but the third requires a considerable number of increments to perform. Sorting the array by frequencies gives effect only for small arrays(= small total number of symbols) and EXTREMELY non-uniform distribution of symbols.So I've suggested to use a tree-like representation of the frequency information (stored inan array). Assume we totally have 8 symbols : 0, 1, ..., 7 and their cumulative frequenciesQ[0] = 0, Q[1], ... Q[7], Q[8] = (the sum of all non-cumulative frequencies). We canbreak the whole frequency interval (0, Q[8]) with Q[4] into 2 subintervals (of lengthsQ[4] and Q[8] - Q[4]), then do the same with the intervals obtained (using Q[2] andQ[6]), and so on. Thus we obtain a binary tree of "breaking points", each node of which

represents breaking of an interval into the two. Let the node contain the breaking locationcounting from the lower bound of an interval. If we now store the resulting tree in anarray using the indices of breaking points (as Q[] elements) in the Q[] array, we willobtain the following array A[]:Q[0] = 0, Q[1], Q[2], Q[3] - Q[1], Q[4], Q[5] - Q[4], Q[6] - Q[4], Q[7] - Q[6] (, Q[8]).Now, obtaining interval bounds and updating the model while encoding/decoding can bedone parallelly. To pass a given symbol while encoding, binary-search it's index in the "0,1, ..., 7, 8" array (starting to compare with "8", then "4" ...) with increasing A[k] when

icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

8/8/2019 VB13

http://slidepdf.com/reader/full/vb13 10/10

going left the node "k". To pass a given point while decoding, binary-search it in A[] withsubtracting A[k] from the point when going right the node "k" (and increasing A[k] if going to the left). Initial state of A[] is not hard to determine (in our case, it is "0, 1, 2, 1,4, 1, 2, 1, 8"), and the overflow preventing (halving the frequencies) is also trivial. Q[8]can be stored in A[0] instead of A[8]. I'm attaching a code shortcut containing

'CFreqModIncr' class implementing all this functionality (sorry, but I didn't have time tomake up a complete project demonstrating it :) (maybe someone will do it "for me andothers" ? ;).

 // *** A short sample.

 // Construct the model.CFreqModIncr model;

 // Initialize to keep 11 symbols and // set up the increment.model.Initialize(11);model.dwIncrement = 1;

 // To pass a symbol with index 'dwIndex' // while encoding, use :DWORD dwLeft, dwRight, dwTotal = model.GetTotalFrequency();model.PassByIndex(dwIndex, dwLeft, dwRight);... // ... and encode the (dwLeft/dwTotal,... // dwRight/dwTotal) interval

 // To decode a symbol, obtain a point // 'dwPoint' in frequency units, then use :DWORD dwLeft, dwRight, dwTotal = model.GetTotalFrequency();DWORD dwIndex = model.PassByPoint(dwPoint, dwLeft, dwRight);... // dwIndex = index of the symbol... // decoded; other 'dw's are to be

 // used in the rest of decoding process ...

model.Uninitialize();