1 / 51

Graphic Device Interface (GDI)

Graphic Device Interface (GDI). Class Form. A Form is a representation of any window displayed in your application. The Form class can be used to create standard, tool, borderless, and floating windows.

tejana
Download Presentation

Graphic Device Interface (GDI)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Graphic Device Interface(GDI)

  2. Class Form • A Form is a representation of any window displayed in your application. • The Form class can be used to create standard, tool, borderless, and floating windows. • The events of the Form class allow you to respond to actions performed on the form. You can use the Activated event to perform operations such as updating the data displayed in the controls of the form when the form is activated. • You can use a form as the starting class in your application by placing a method called Main() in the class. In the Main() method add code to create and show the form.

  3. Some Event functions of Form Note: EventArgs is parent class of all other *** EventArgs

  4. Class Point • Namespace:System.Drawing • Constructor Point p = new Point(int x, int y); y x

  5. Class Rectangle • Constructor Rectangle r = new Rectangle( Point(x, y), Size(w, h)); Rectangle r = new Rectangle( int x, int y, int w, int h); y x w h

  6. class Color • Some staticColor objects Color.Red Color.Yellow Color.Blue • Color object can be obtained from RGB formation Color c1 = Color.FromArgb(200, 128, 48); • We also can use 0 a  255 to control color a = 255 means opaque, a = 0 means transparent a= 180 means half transparent • For example: Color c2 = Color.FromArgb(a, c1); Color c2 = Color.FromArgb(a, 200, 128, 48);

  7. Class Pen • Namespace:System.Drawing • Pen object draws a line of specified width and style. • Constructor Pen(Color object, int width); Pen p = new (Color.Red, 3) • Some Pen objects can be got from class Pens Pens.Red Pens.Yellow Pens.Blue They all have width 1

  8. Class Font Constructor Font( FontFamily family, float Size, FontStyle style ); Example Font f = new Font("Arial", 36, FontStyle.Bold|FontStyle.Italic );

  9. Class Brush • Namespace:System.Drawing • Brush object used to fill the interiors of graphical shapes such as rectangles, ellipses, pies, polygons, and paths. • This is an abstract class. Use derived classes such as : SolidBrush(Color object) TextureBrush(Image object) (In Namespace: System.Drawing.Drawing2D) LinearGradientBrush(Point1, Point1, Color1, Color2) HatchBrush(HatchStyle, Color1, Color2)

  10. Class Graphics • Namespace:System.Drawing • The Graphics class provides methods for drawing objects to the display device. • A Graphics object is associated with a specific device context, which means every Form has a built-in Graphics object. • The following method is wrong: Graphics g = new Graphics()

  11. Some Methods of Graphics

  12. Operations in OnPaint() All code inside OnPaint() will be executed when the application window is showing to the screen. protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics ; Pen blackPen = new Pen(Color.Black, 3); Rectangle rect = new Rectangle( 0, 0, 200, 100); g.DrawEllipse(blackPen, rect);

  13. Pen redPen = new Pen(Color.Red, 3); Point p1 = new Point(150, 150); Point p2 = new Point(500, 300); g.DrawLine(redPen, p1, p2); g.FillEllipse(new SolidBrush(Color.FromArgb (180,Color.Green)), new Rectangle(50,50, 200,200)) ; g.FillRectangle(new SolidBrush(Color.Red), 20, 20, 50, 50); g.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.Yellow)), 40, 40, 50, 50); HatchBrush hb= new HatchBrush(HatchStyle.ForwardDiagonal, Color.Green, Color.FromArgb(100, Color.Yellow)); g.FillEllipse(hb, 250, 10, 100, 100); Image newImage = Image.FromFile("dog.gif"); g.DrawImage(newImage, new Point( 300, 100));

  14. string drawString = "UH Sugarland"; Font drawFont = new Font("Arial", 36, FontStyle.Bold|FontStyle.Italic ); SolidBrush drawBrush = new SolidBrush(Color.Red); PointF drawPoint = new Point(50, 300); g.DrawString(drawString, drawFont, drawBrush, drawPoint); LinearGradientBrush lb = new LinearGradientBrush ( new Point(200,200), new Point(400,300), Color.Yellow , Color.Blue); g.FillRectangle(lb, 200, 200, 200, 100); }

  15. Output

  16. Invalidate(Rectangle rect) operator Invalidate (Rectangle rect) is an operator to remove all graphic images within the specified rectangle and call OnPain() function to redraw images within this rectangle. If we want redraw all images, call Invalidate( new Rectangle (0, 0, this.Width, this.Height ) );

  17. Class Bitmap class Image is an abstract class. class Bitmap is a subclass of Image Constructors: Bitmap(Image img); // from Image object Bitmap(Stream stream); // from internet Bitmap(String file_name); // from file Bitmap(int w, int h); // with specified size Methods: public Color GetPixel ( intx, inty ); public void SetPixel ( intx, inty, Colorcolor); public void Save(string fname, ImageFormatfmt); public void Save(Stream stream, ImageFormatfmt); Example: bmp.Save(Response.Outputstream, ImageFormat.Jpeg);

  18. Class HttpWebRequest HttpWebRequest class is subclass of WebRequest that enable the user to interact directly with servers using HTTP. Request object Creation: request =(HttpWebRequest) WebRequest.Create(string url); Get Response object response =(HttpWebResponse) request.GetResponse(); Get Stream from Response object stream = response.GetResponseStream();

  19. using System; //Server Side Code: using System.Net.Sockets; using System.IO; public class AsynchIOServer { public static void Main() { TCPListener tcpListener = new TCPListener(10); tcpListener.Start(); Socket socket = tcpListener.Accept(); if (socketForClient.Connected) { Console.WriteLine("Client connected"); NetworkStream stream = new NetworkStream(socket); StreamWriter streamWriter = new StreamWriter(stream); StreamReader streamReader = new StreamReader(stream);

  20. string theString = "Sending"; streamWriter.WriteLine(theString); Console.WriteLine(theString); streamWriter.Flush(); theString = streamReader.ReadLine(); Console.WriteLine(theString); streamReader.Close(); stream.Close(); streamWriter.Close(); } socketForClient.Close(); Console.WriteLine("Exiting..."); } }

  21. using System; //Client Side Code: using System.Net.Sockets; using System.IO; public class Client {static public void Main( string[] Args )   {   TCPClient client;try      {    client= new TCPClient("localHost", 10);}catch      {         Console.WriteLine(            "Failed to connect to server at {0}:999", "localhost");return;      }      NetworkStream stream = client.GetStream();      StreamReader streamReader =new StreamReader(stream);      StreamWriter streamWriter = new StreamWriter(stream);

  22. try      {         string outputString;// read the data from the host and display it         {            outputString = streamReader.ReadLine();               Console.WriteLine(outputString);               streamWriter.WriteLine("Client Message");               Console.WriteLine("Client Message");               streamWriter.Flush();                    }           }    catch      {         Console.WriteLine("Exception reading from Server");      }      stream.Close();   }}

  23. string theString = "Sending"; streamWriter.WriteLine(theString); Console.WriteLine(theString); streamWriter.Flush(); theString = streamReader.ReadLine(); Console.WriteLine(theString); streamReader.Close(); stream.Close(); streamWriter.Close(); } socketForClient.Close(); Console.WriteLine("Exiting..."); } }

  24. ColorMatrix Defines a 5x5 matrix that contains the coordinates for the RGBA space. Several methods of the ImageAttributes class adjust image colors by using a color matrix. The matrix coefficients constitute a 5x5 linear transformation that is used for transforming ARGB homogeneous values. For example, an ARGB vector represented as alpha, red, green, blue, and w, where w is always 1. entries are Matrix00, Matrix01, Matrix02, Matrix03, Matrix04, . . .

  25. ImageAttributes.SetColorMatrix An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a color-adjustment matrix for the default category, a different color-adjustment matrix for the bitmap category, and still a different color-adjustment matrix for the pen category. The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category. The call myImageAttributes.SetColorMatrix(cm) is equivalent to the call myImageAttributes.SetColorMatrix(cm, ColorMatrixFlag.Default). ColorMatrixFlag.Default specifies that all colors (including grays) are adjusted by the color-adjustment matrix.

  26. Brightness - The Algorithm Conceptually, Brightness is a very simple algorithm.  This simplicity is reflected in the code.  This specific implementation has some features that are noteworthy. To make this algorithm as fast as possible, I separated Lightening and Darkening.  This is for two reasons.  If we are lightening we will never have to check if the color value is below zero, the reverse is true for darkening.  We just saved one IF statement for every color channel.  The more important reason however is that a byte only holds values between 0 and 255.  There is no data type that holds values from -255 to 255 which is our range of acceptable values.  This means if we didn't separate Lightening and Darkening, adjustment would have to be an int and we would have to cast multiple times every loop iteration.  This is why our function accepts the bool darken.

  27. Contrast Contrast is easy to understand visually.  Artistically, contrasting colors are colors that are opposite on the color wheel -- colors that are opposites.  In a high contrast image, you can see definite edges and the different elements of that image are accented.  In a low contrast image, all the colors are nearly the same and it's hard to make out detail. Contrasting colors in terms of a computer's representation of an image, means the "primary colors" or the colors with color components of 0 or 255 (Min and Max).  Black, White, Red, Green, Blue, Cyan, Magenta, and Yellow are the high contrast colors.  When all the colors in an image are around one single color, that image has low contrast.  Grey is the usual color of choice because it rests exactly in between 0 and 255 (127 or 128). Contrast is a complicated operation.  It is hard to formulate a "general algorithm".  Here is the closest representation:

  28. Contrast // [0, 1]New_Value = Old_Value / 255 //Converts to a percent //[-.5, .5]New_Value -= 0.5 //Centers on 0 instead of .5//[-127.5, 127.5], usually [-1, 1]New_Value = New_Value* Contrast_factor //Adjusts by Contrast_Value//[-127, 128]New_Value += 0.5 //Re-add .5 (un-center over 0)//Re-multiply by 255 (un-convert to percent)//[-32385, 32640], usually [0, 255]New_Value *= 255//Clamp[0, 255]if(New_Value > 255) New_Value = 255if(New_Value < 0) New_Value = 0

  29. Contrast private static Bitmap AdjustBrightness_24bppRgb (Bitmap bmp, byte adjustment, bool darken){ int color = 0;//Ready the whole bitmap for reading and writing BitmapData bmpData = bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); unsafe {//Sets the pointer to the first pixel byte * ptr = (byte *)bmpData.Scan0;/*Line offset for pointer. Since we only have 3 bytes per pixel in this format and since lines are aligned at 4 byte boundaries we may need this for certain sized bitmaps)*/ int remain = bmpData.Stride - bmpData.Width * 3;

  30. //Check for darken/lighten outside of loop to improve speed if (darken == false) { for(int y = 0; y < bmpData.Height; y++) { for(int x = 0; x < bmpData.Width * 3; x++) { color = (int)ptr[0] + adjustment; if (color > 255) color = 255; ptr[0] = (byte)color; ptr ++; } ptr += remain; } }

  31. else //(darken == true) { for(int y = 0; y < bmpData.Height; y++) {for(int x = 0; x < bmpData.Width * 3; x++) { color = (int)ptr[0] - adjustment;if (color < 0) color = 0; ptr[0] = (byte)color; ptr ++; } ptr += remain; } } } bmp.UnlockBits(bmpData);return bmp;}

  32. IntPtr type The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems. The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers. IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles. The IntPtr type is CLS-compliant, while the UIntPtr type is not. Only the IntPtr type is used in the common language runtime. The UIntPtr type is provided mostly to maintain architectural symmetry with the IntPtr type. This type implements the ISerializable interface.

  33. All about Unsafe Code in C# C# .net hides most of memory management, which makes it much easier for the developer. Thanks for the Garbage Collector and the use of references. But to make the language powerful enough in some cases in which we need direct access to the memory, unsafe code was invented. Commonly while programming in the .net framework we don’t need to use unsafe code, but in some cases there is no way not to, such as the following: • Real-time applications, we might need to use pointers to enhance performance in such applications. • External functions, in non-.net DLLs some functions requires a pointer as a parameter, such as Windows APIs that were written in C. • Debugging, sometimes we need to inspect the memory contents for debugging purposes, or you might need to write an application that analyzes another application process and memory. • Unsafe code is mostly about pointers

  34. Advantages of Unsafe Code in C#: • Performance and flexibility, by using pointer you can access data and manipulate it in the most efficient way possible. • Compatibility, in most cases we still need to use old windows APIs, which use pointers extensively. Or third parties may supply DLLs that some of its functions need pointer parameters. Although this can be done by writing the DLLImport declaration in a way that avoids pointers, but in some cases it’s just much simpler to use pointer. • Memory Addresses, there is no way to know the memory address of some data without using pointers.

  35. Disadvantages of Unsafe Code in C# • Complex syntax, to use pointers you need to go throw more complex syntax than we used to experience in C#. • Harder to use, you need be more careful and logical while using pointers, miss using pointers might lead to the following: • Overwrite other variables. • Stack overflow. • Access areas of memory that doesn’t contain any data as they do. • Overwrite some information of the code for the .net runtime, which will surely lead your application to crash. • Your code will be harder to debug. A simple mistake in using pointers might lead your application to crash randomly and unpredictably. • Type-safety, using pointers will cause the code to fail in the .net type-safety checks, and of course if your security police don’t allow non type-safety code, then the .net framework will refuse to execute your application.

  36. Formation unsafe class Class1{//you can use pointers here!} Or only some class members can be declared as unsafe: class Class1 { //pointer unsafeint * ptr;unsafe voidMyMethod(){ //you can use pointers here}}

  37. Introduction • This is a resource manager class library.You can put any type of resources such as image,icon,Wave,MIDI and so on. in the executable of your application and then load it from the EXE or DLL file by using the methods of this library.  What is a Resource ? • A resource can be any type of file that you can put it in an assembly at design time and get it out at runtime.Any file can • be a resource,Such as Icon,Bitmap,Wave, Avi, XML and so on.

  38. What is advantage of resources ? • With compressing resource files inside the main executable or a separate DLL file, you can hide any extra files that used in the application from the user. This has some benefits : • inexpert users can't change or remove the vital needed files from the application directory and cause the application to crash. •  You can put everything in a single file and avoid the application directory to be bustled

  39. How to Add Resources • You can use the Resource Designer to add or edit resources for your project. • In VS.NET IDE you can do the following steps to add an existing resource at design time to your project : • Create a windows application or class library project. • Right click on the selected project in Solution Explorer and select Add->Existing Item. • Find the resource file you want to add to the project and press ok. • Right click on the added resource file in solution explorer and click properties. • In the Properties tab of selected file,change the 'Build Action' from 'Content' to 'Embedded Resource'. The last step is for compressing the resource file into the assembly and creating a single file.

  40. How this library works • After adding the resource file(s) to an assembly,for using that file(s),we need to load the assembly at runtime and then fetch the resource(s) out from it. • MS .NET has many useful functions for working with  assembelies at runtime. • Yes,The System.Reflection.Assembly is our friend. • The Proshot.ResourceManager library uses Assembly functions to load the target assemblies and pull the resources out from them. • You can load an assembly module at runtime and do many actions with it. • This class has 3 constructors. The first constructor expects a string as its argument that specifies the DLL or Executable file path and name that your desired resource is compressed in that. Use this constructor if resource file(s) is in an external EXE or Dll other than current executable or Dll.

  41. Introduction This chapter divides neatly into two main topics. First, we’ll consider the classes provided by the .NET Framework classes, which meet the lower-level data transfer requirements of the streams-based I/O framework. These classes further divide into stream classes and file system classes.that is, classes that actually represent data streams, and classes that represent file system objects such as files and directories. Then we’ll look at how you can enhance any custom class to allow it to fit seamlessly into the standard I/O framework. This enhancement is based on a standard attribute that marks your class as capable of being serialized. The serialization process is used in conjunction with the streams classes to stream your custom class objects from one place to another.in memory, to a remote location, or to persistent storage. As part of our exploration of the streams framework, we’ll consider the different types of stream, types of file system objects, and potential application environments, including Microsoft Windows.based and Web-based environments.

  42. Stream Classes

  43. Two classes derived from Stream but not listed in Table 1 are offered in other namespaces. The NetworkStream class represents a Stream over a network connection and resides in the System.Net.Sockets namespace, and the CryptoStream class links data streams to cryptographic transformations and resides in the System.Security.Cryptography namespace. The design of the Stream class and its derivatives is intended to provide a generic view of data sources and destinations so that the developer can interchangeably use any of these classes without redesigning the application. In general, Stream objects are capable of one or more of the following: • Reading The transfer of data from a stream into a data structure, such as an array of bytes • Writing The transfer of data from a data structure into a stream • Seeking The querying and modifying of the current position within a stream Note that a given stream might not support all these features. For example, NetworkStream objects don't support seeking. You can use the CanRead, CanWrite, and CanSeek properties of Stream and its derived classes to determine precisely which operations a given stream does in fact support.

  44. Introduction • This is a resource manager class library.You can put any type of resources such as image,icon,Wave,MIDI and so on. in the executable of your application and then load it from the EXE or DLL file by using the methods of this library.  What is a Resource ? • A resource can be any type of file that you can put it in an assembly at design time and get it out at runtime.Any file can • be a resource,Such as Icon,Bitmap,Wave, Avi, XML and so on.

  45. What is a Resource ? • A resource can be any type of file that you can put it in an assembly at design time and get it out at runtime. • Any file can be a resource, Such as Icon, Bitmap, Wave, Avi, XML and so on. • With compressing resource files inside the main executable or a separate DLL file, you can hide any extra files that used in the application from the user.

  46. Advantages to useResource • Inexpert users can't change or remove the vital needed files from the application directory and cause the application to crash. •  You can put everything in a single file and avoid the application directory to be bustled • After starting a program, all resource files are in the memory. Therefore programs can run faster if using Resource data instead of directly reading files from hard disk.

  47. How to addResource • Right click on the selected project in Solution Explorer and select AddExisting Item.

  48. 2. Set Files of Type first, then search your hard disk to find the resource file you want to add to the project and press Open.

  49. 3. Right click on the added resource file in solution explorer and click properties.

  50. 4. In the Properties tab of selected file, go to 'Build Action' and change it from 'Content' to 'Embedded Resource'.

More Related