Home Programming Delphi Programming Projects

Delphi Programming Projects

By William Duarte
books-svg-icon Book
eBook $29.99 $20.98
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99 $20.98
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Building an Instagram Clone
About this book
Delphi is a cross-platform programming language and software development kit that supports rapid application development for Microsoft Windows, Apple Mac OS X, Android, and iOS. With the help of seven practical projects, this book will guide you through the best practices, Delphi Run-Time Library (RTL) resources, and design patterns. Whether you use the Visual Component Library (VCL) or FireMonkey (FMX) framework, these design patterns will be implemented in the same way in Delphi, using Object Pascal. In the first few chapters, you will explore advanced features that will help you build rich applications using the same code base for both mobile and desktop projects. In addition to this, you’ll learn how to implement microservice architecture in Delphi. As you get familiar with the various aspects of Delphi, you will no longer need to maintain source code for similar projects, program business rules on screens, or fill your forms with data access components. By the end of this book, you will have gained an understanding of the principles of clean code and become proficient in building robust and scalable applications in Delphi.
Publication date:
May 2019
Publisher
Packt
Pages
248
ISBN
9781789130553

 

Building an Instagram Clone

The world has changed. We are in the new digital age where, every day, more and more apps are available to the users. So, what really grabs attention, since we have so many options available? Features, user experience, rich design? We can say that, with Delphi, we have all the ability to develop rich applications, both graphically and in terms of functionality.

A major challenge for Delphi developers is the paradigm shift between desktop and mobile platforms. The way to develop and draw a form is different, of course; however, many developers program as if they were still working with a Delphi 7 IDE.

If you are this type of developer and want to learn more about responsive design and how to change your desktop mindset for mobile, then this is an ideal chapter for you.

We have chosen an application already on the market—Instagram—to better elucidate these insights and this paradigm shift.

In this Delphi version of Instagram, you will be introduced to the following topics:

  • Mindset between desktop and mobile
  • Creating responsive layouts
  • Creating buttons with Scalable Vector Graphics (SVG) icons
  • Interacting with the camera
  • Sharing photos

The knowledge necessary for understanding this chapter is basic. Experience with Delphi is not necessary; minimal knowledge of the IDE and some components, such as buttons, edits, and list views, is sufficient.

 

Technical requirements

 

Project overview

The goal of this project is to enable you to better understand the use of visual components and the concept of responsive design, and introduce the concepts of actions and use them to take beautiful photos.

The estimated build time is two to five minutes.

 

Getting started

It is necessary to have access to the internet to access sites that offer SVG.

No download is required.

 

Mindset difference between desktop and mobile

When smartphones became essential and the emergence of the three major mobile OS competitors (iOS, Android, and Windows phone—this last one has been discontinued) took shape, developers were confused. After all, who was not accustomed to responsiveness or smaller screens? Before diving into this new world, you need to understand some important things.

Developing for the Windows desktop, we have some benefits—available memory, ease of interface design (usually in resolutions of at least 1,024 x 768), and others. Most of these features make the programmer's life much more focused on the logic of the application without worrying too much about available computer resources or the like.

When web applications began to emerge with their HTTP protocol in the best request-response style, a new concept of development was created. The programmer had to adapt to the new markup languages (HTML and CSS) and had to separate their application in what we call the server/client side. So, anyone who previously programmed into a single programming language (such as Java or C#) had to adapt to learn markup languages. And, with a need for insertion in the web world, the programmer needed to deal with screen sizes. On the other hand, the applications should be more and more responsive to work more in the varied sizes of screen, from tiny phones to tablets and desktops; not to mention the limitations of the hardware, since they have less processing power and memory than desktop computers.

Mobile has combined the advantages of the previous two along with their disadvantages. If it was said in the web application that everything was on the web, that is to say, for any user access just entering the site, the mobile brought back the desktop concept. The application is installed in the device, and, if you have to upgrade the application, you have to do so for each device. We return to the same situation as desktop applications.

Having limited hardware, including reduced screen size and the absence of peripherals means that the challenge for the mobile developer is more complex

Before you start reading into this topic, you must abandon certain preconceptions, such as the idea that developing for mobile is the same as doing so for web or desktop. No, it's not! Remember that your user is on a limited device and does not have any peripherals for assistance, such as a mouse or keyboard.

Follow these steps to learn about viewing for different screen types:

  1. Open the Delphi IDE and create a Multi-Device Application. Note that different screen types will have different viewing characteristics:
  1. Select one Android or iPhone view.
Note that the display format is changed. Try working on master view and switch views to keep track of the layout of your components on the form.

When you work with a different view of the master, Delphi will create a new .FMX file in your project folder. This file will contain the positions of the components for that particular screen format. The paradigm shift is not just about the size or the screen format, but the Delphi IDE helps us identify those nuances.

Range of sizes

There are a range of sizes used to determine the view that is used in Android apps. Note that the runtime does not require an exact match to select a view. The runtime chooses the closest match. The following table shows the ranges for each view, specified in landscape coordinates:

View Name

Minimum Size

(Pixels)

Maximum Size

(Pixels)

PPI
Android 3.5'' Phone 800x500 1,000x600 320
Android 4'' Phone 1,1168x730 1,360x850 320
Android 5'' Phone 1440x900 1,708x960 320
Android 7'' Tablet 1708x960 1,920x1,200 320
Android 10'' Tablet 2,400x1,500 2,560x1,600 320

It is possible to visualize the layout of the forms in the device in real time by looking at the Berlin version design time. Fantastic, isn't it? To do this, download the Fire UI Live Preview application from your platform store (Google Play: http://docwiki.embarcadero.com/RADStudio/Rio/en/FireUI_App_Preview, or Apple Store: https://itunes.apple.com/us/app/fireui-app-preview-10.1-berlin/id1090861997) or install directly via the C:\Program Files (x86)\Embarcadero\Studio\20.0\LivePreview\ path.

FireUI Live Preview is a server/client multi-device tool that allows you to broadcast the active form of your application, in real time, to several devices simultaneously.

 

Creating responsive layouts

In this topic, you will learn how to work with responsive layouts in Delphi using FireMonkey (FMX). For the examples, we will use Delphi Tokyo. Let's have a look at the required steps:

  1. To start, open Delphi and create a new project by navigating to File | New | Multi-Device Application-Delphi and select Blank Application:

Adjust the style for Android; for example, for the view, we will continue in the Master view.

Give preference to working in the Master view. During development, if you want to modify views and add new controls to your form, the responsiveness properties will not be inherited. For example, when adding a TButton component to a 4-inch Android view, properties will be lost if you create to modify for a different view, such as iPhone. In the Master view, all the characteristics will be kept, keeping their proportions clear, by the platform.
  1. Add a Toolbar component to your form.
  2. Create two buttons inside Toolbar.
  3. Select the two buttons and align to the left.
  4. Modify the margins to 5 on each property.
  5. Save your project and run the application for a Windows platform.
  6. Then, select the first button that is already configured and modify the StyleLookup property by selecting the cameratoolbutton option. Notice that the button icon is then changed to a specific camera icon.
  7. Add another Toolbar component, but leave it with bottom alignment. In this toolbar, add a button, align it to the right, and change its margins to 5, as in the top buttons. This button will exit the application.
  8. Finally, add a TLayout component to the center of your form so that it fills the empty area and align it when using Client.
  9. Also, modify StyleLookup for the missing buttons. For the button next to the camera, select searchtoolbutton, because, through this, we will search the already-saved images in the device. For the last button, select escapetoolbutton in the StyleLookup property, because, with this button, we will leave the application.

TLayout

The FireMonkey components have an owner, parent, and children. If you put any component on a form, it becomes the owner and parent of the component.

Using properties such as Position, Align, Margins, and Padding with anchors, you will turn your app in to a responsive application.

Note that, even if you resize the form, the buttons remain aligned to the left, respecting the margins, and are inside the toolbar.
FireMonkey layouts are containers for other graphics objects that can be used to build elegant-looking forms. FireMonkey layouts extend the functionality of the controls for the arrangement and scaling of controls.

To achieve rich interfaces using TLayout, use more than one layout and the organization properties of the child controls in the layouts.

If everything went well here, you will have a form as shown in the following screenshot:

Try creating new views and see the resulting alignment. This is the basic principle for developing a responsive application in FireMonkey.

If you want to view the format with the screen rotated, there is a button to rotate the screen. With this, you can view the layout on the screen in a different format as shown in the following screenshot:

Look at the different types of layouts and their characteristics. For project types where you need to insert many components, use the ScrollBox so you can have a scrolling effect on your form.

 

Creating buttons with SVG icons

In the previous project, we created the main basic layout. Later on, we created photo and sharing events. In this project, we will work with the use of SVG icons, which are infinitely smaller in size in relation to the allocation of space.

SVG is an XML-based vector graphics format that can scale to any size without losing clarity. SVG images and their characteristics are defined in XML text files. That is, they can be searched, indexed, scripted, and compressed. Like XML files, SVG images can be produced and modified with any editing software.

We will use 100% native components in order to use an SVG image. To do this, follow this step by step:

  1. From the Tool Pallet, select TRectangle. Add in the toolbar created previously, use the property, and align the rectangle by setting it to the center. You will now have a rectangle centered in the toolbar.
  2. Add a speed button inside this same rectangle. Note that in the Structure pane, the button is contained within the shape. Do the same with the TPath component, but leave it as the child of the speed button. Align both to Center.
  3. Clear the Text property of the new speed button:

The structure of your application should be like this, with the components nested.

  1. Okay, now that you have the basic structure assembled on your form, it's time to choose an SVG icon to illustrate this button. The purpose of this button is to execute the share function when clicked. So, we can now share a photo. You can search the internet for various SVG icons. In this example, you can copy the SVG code at http://materialdesignicons.com/ to use in our application.

  1. The icon used is Instagram. It is important to note that in certain tools or websites, such as materialdesignicons.com, you have the functionality to view the SVG code and also to be able to download the binary file. A simpler way to get the SVG code is to view it online:

In this case, to copy the correct information from the SVG vector, go directly to the d= property and copy its content. This property contains the icon code:

  1. Once you have the content of the SVG vector, you can include it in your Delphi application using the TPath component. To do so, follow these steps:
    1. Select the TPath component.
    2. Select the Data property.
    3. Input the SVG content and save as shown in the following screenshot:
Note that by entering the content of the data tag in the TPath component, you can preview the image.

This is what the Instagram icon looks like:

You can color the icon in the Fill property, including Gradient. To remove the border, just leave it as None in the Stroke.Kind property at Object Inspector:

You can also change the color of your button as long as it is inside the rectangle. To do this, change the Fill.Color property of the rectangle and watch the magic happen.

In the first two steps, we created a new button and centered the toolbar. Notice that this button has a new component, the TPath. The TPath is inside our button. This causes the image, which we copy from the internet appears contained in the component. In steps three, four, and six, we located the SVG icon and copied its content through the d property. With the contents of the image copied, we then go to the TPath component, making it display the same icon that was selected, in this case, Instagram.

If you're not familiar with SVG icons, feel free to browse through a variety of other sources. There are numerous websites for downloading icons in various formats, including SVG.
 

Interacting with the camera

There are at least two ways to take a picture with FireMonkey—the first, for the lazy, is to use an ActionList, linking the action of taking a photo to a visual component, such as a button. In this case, your application will request access to the device's camera application.

The second form, however, gives us more freedom in terms of functionality, using TCameraComponent. With it, you can set the resolution, specify the type of camera (front or back) that can be used, choose to use the flash, and you can even create your own flashlight application.

Lights, camera, and action!

Now that we have the main screen properly built with its main components anchored, we can work on the main functionality—recording moments! Using the same project as the previous recipes, we will finally develop the code to capture images:

  1. First, add a TImage component to your form and set its alignment to alClient, filling all layout content. We will use this TImage to display the photo. Now, do the same for a non-visual component, called ActionList. Enter this into the form. Change the TImage property and name it as ImgInsta.
  2. With the right-click on ActionList, open the ActionList Editor option.
    With the keyboard, click Ctrl + Insert to open the dialog containing the options; you can also go with the mouse on the New button and insert the new action. The action we want is TTakePhotoFromCameraAction:

In this project, we will capture the image in two ways, the first with a standard action and the other using the IFMXCameraService interface.

  1. Let's create the DoDidFinish procedure:
procedure TForm1.DoDidFinish(Image: TBitmap); begin ImgInsta.Bitmap.Assign(Image); end;
  1. In this procedure, the image parameter, which will come from the camera, will be assigned to the TImage component in our form. Remember to assign this procedure to the OnDidFinishTaking event of TTakePhotoFromCameraAction:
procedure TForm1.TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap);
begin
DoDidFinish(Image);
end;

In the next few steps, you will understand why this is redundant.

  1. We can create a new default action, which will fetch images already saved in the device library. Repeat the process to add a new action to your ActionList; however, this time select the TTakeFromLibrary action.
If you want your application to automatically save the pictures taken by a device camera to the device photo library, set the TCustomTakePhotoAction.NeedSaveToAlbum property to True.
  1. When selecting the event of this new action, the code is exactly the same code that was made in TTakePhotoFromCameraAction:
procedure TForm1.TakePhotoFromLibraryAction1DidFinishTaking(Image: TBitmap);
begin
DoDidFinish(Image);
end;
Note that since the image comes from a parameter, which comes from the action, it allows you to use exactly the same line of code.
  1. Bind the respective actions to their execution buttons:
  1. Let's increase the project a bit more, including an extra button added to the top in the first toolbar, only this time, right-aligned. This button will also take a picture, but, using the IFMXCameraService interface. To perform such an act, include the following units in the uses clause of your form:
uses
  FMX.MediaLibrary, FMX.Platform, System.Messaging;

  1. Add another procedure to capture the message coming from the device and thus identify an action to take photos:
procedure DoMessageListener(const Sender: TObject; const M: TMessage);

Its implementation is shown in the following code snippet:

procedure TForm1.DoMessageListener(const Sender: TObject; const M: TMessage);
begin
if M is TMessageDidFinishTakingImageFromLibrary then
ImgInsta.Bitmap.Assign(TMessageDidFinishTakingImageFromLibrary(M).Value);
end;
  1. Encode the FormCreate procedure:
procedure TForm1.FormCreate(Sender: TObject);
begin
TMessageManager.DefaultManager.SubscribeToMessage(
TMessageDidFinishTakingImageFromLibrary, DoMessageListener);
end;
  1. To conclude, let's encode the onClick event of the newly added button:
procedure TForm1.Button3Click(Sender: TObject);
var
Service: IFMXCameraService;
Params: TParamsPhotoQuery;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXCameraService,
Service) then
begin
Params.Editable := True;
// Specifies whether to save a picture to device Photo Library
Params.NeedSaveToAlbum := True;
Params.RequiredResolution := TSize.Create(640, 640);
Params.OnDidFinishTaking := DoDidFinish;
Service.TakePhoto(Button3, Params);
end
else
ShowMessage('This device does not support the camera service');
end;

We divide this project into two parts, where, in the first part, we use an ActionList to take a picture. These actions require very little programming; however, they will not work on Windows platforms. In the second part, when using the IFMXCameraService interface, we have the freedom to implement our codes with a few more lines but greater freedom. We can also include parameters that allow us to, for example, set the minimum resolution and define whether we will save the image to the device as well.

You should also check the TCameraComponent component. You can take your photos without even directing them to your device's camera, including video recordings.

 

Sharing photos

FireMonkey's basic sharing service does not differ from the way we interact to take a photo; that is, we can use a standard action in our ActionList1 to create a new event where we share the photo you just took.

Now that our application is responsive and is properly recording the most important moments through photographs, let's share! Using the same example from previous recipes, we will now develop the button event we created with the SVG icon.

The following steps will show you how to share the photos using FireMonkey:

  1. Create a new action in the ActionList1, in the Media Library category, to display the share center. Select the ShowShareSheetAction1 action:
  1. The event is now different; in order to share, it is necessary to assign what you want to share. In our project, we will share a photo. For this, we must program the OnBeforeExecute event of this action:

The following is the code for the OnBeforeExecute event:

procedure TForm1.ShowShareSheetAction1BeforeExecute(Sender: TObject);
begin
ShowShareSheetAction1.Bitmap.Assign(ImgInsta.Bitmap);
end;
  1. Now, to finish, just assign the newly coded action the Action property of our button. You can use Structure pane and select the TSpeedButton (which has the TPath component is inside it) component with the Instagram logo. With everything ready, when taking a photo it will be filled through the TImage component that can be shared.

The following screenshot shows the form view at development time:

The following screenshot shows the form view running on an Android mobile:

Finally, the application images are still at design time in Delphi and are already running on an Android device.

 

Summary

We have introduced through this mini Instagram clone how to work with basic responsive design, making sure that, regardless of the size of the screen, our controls adjust according to the screen. Then, through the TPath component, we included icons in SVG format, drastically reducing the size of the images and icons thanks to vectorization.

Our code was simple and consisted of only three lines. At a minimum, we can take a photo, choose a photo from the library, and share with friends. All this is done using ActionList and interfaces already done in the FireMonkey library.

In the next chapter, you'll be introduced to the wonderful world of APIs. Not only is it possible to consume Facebook API services, but you can develop your application on the platform by interacting with Delphi.

Delphi is this simple, RAD, and practical!

 

Further reading

About the Author
  • William Duarte

    William Duarte is a Delphi Certified Developer and Embarcadero Regional MVP Coordinator. He began his career in 2005 as a programmer. He was recognized as an internationally certified Retail Technical Consultant by Retail Pro in 2007. He is a specialist in commercial automation and desktop/mobile development, and the author of a book in PortugueseDelphi for Android and iOS, by Brasport, 2015. He is currently working as a consultant for the Brazilian Navy and retail chain stores.

    Browse publications by this author
Latest Reviews (19 reviews total)
Ótimos produtos. Preços ótimos.
Buono per affrontare un argomento che il lettore magari non conosce, ma forse non approfondito al massimo nel caso servano maggiori dettagli implementativi
You can learn programming in a self-taught way.
Delphi Programming Projects
Unlock this book and the full library FREE for 7 days
Start now