archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • An iOS 5 iPad Graphics Tutorial using Quartz 2D and Core Image - Techotopia
    must fit and then calling the CGContextAddEllipseInRect function void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 8 0 CGContextSetStrokeColorWithColor context UIColor greenColor CGColor CGRect rectangle CGRectMake 60 300 650 400 CGContextAddEllipseInRect context rectangle CGContextStrokePath context When compiled the above code will produce the following graphics Figure 48 5 In order to draw a circle simply define a rectangle with equal length sides a square in other words Filling a Path with a Color A path may be filled with a color using a variety of Quartz 2D API functions Rectangular and elliptical paths may be filled using the CGContextFillRect and CGContextFillEllipse functions respectively Similarly a path may be filled using the CGContextFillPath function Prior to executing a fill operation the fill color must be specified using the CGContextSetFillColorWithColor function The following example defines a path and then fills it with the color red void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextMoveToPoint context 355 300 CGContextAddLineToPoint context 555 500 CGContextAddLineToPoint context 355 700 CGContextAddLineToPoint context 155 500 CGContextAddLineToPoint context 355 300 CGContextSetFillColorWithColor context UIColor redColor CGColor CGContextFillPath context The above code produces the following graphics on the device or simulator display when executed Figure 48 6 The following code draws a rectangle with a blue border and then once again fills the rectangular space with red void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 25 0 CGContextSetStrokeColorWithColor context UIColor greenColor CGColor CGRect rectangle CGRectMake 60 300 650 400 CGContextAddRect context rectangle CGContextStrokePath context CGContextSetFillColorWithColor context UIColor redColor CGColor CGContextFillRect context rectangle When added to the example application the resulting display should appear as follows Figure 48 7 Drawing an Arc An arc may be drawn by specifying two tangent points and a radius using the CGContextAddArcToPoint function for example void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 2 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGContextMoveToPoint context 100 100 CGContextAddArcToPoint context 100 200 300 200 100 CGContextStrokePath context The above code will result in the following graphics output Figure 48 8 Drawing a Cubic Bézier Curve A cubic Bézier curve may be drawn by moving to a start point and then passing two control points and an end point through to the CGContextAddCurveToPoint function void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 10 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGContextMoveToPoint context 100 600 CGContextAddCurveToPoint context 475 0 750 600 200 300 CGContextStrokePath context The above code will cause the curve illustrated in Figure 48 9 to be drawn when compiled and executed in our example application Figure 48 9 Drawing a Quadratic Bézier Curve A quadratic Bézier curve is drawn using the CGContextAddQuadCurveToPoint function providing a control and end point as arguments having first moved to the start point void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 8 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGContextMoveToPoint context 10 600 CGContextAddQuadCurveToPoint context 375 0 750 600 CGContextStrokePath context The above code when executed will display a curve that appears as illustrated in the following figure Figure 48 10 Dashed

    Original URL path: http://www.techotopia.com/index.php/An_iOS_5_iPad_Graphics_Tutorial_using_Quartz_2D_and_Core_Image (2016-02-13)
    Open archived version from archive


  • Basic iOS 5 iPad Animation using Core Animation - Techotopia
    object For example to change the scale of a UIView object named myView by a factor of 2 in both height and width myView transform CGAffineTransformMakeScale 2 2 Similarly the UIView object may be rotated using the CGAffineTransformMakeRotation which takes as an argument the angle in radians by which the view is to be rotated The following code for example rotates a view by 90 degrees myView transform CGAffineTransformMakeRotation 90 M PI 180 The key point to keep in mind with transformations is that they become animated effects when performed within an animation block The transformations evolve over the duration of the animation and follow the specified animation curve in terms of timing Combining Transformations Two transformations may be combined to create a single transformation effect via a call to the CGAffineTransformConcat function This function takes as arguments the two transformation objects that are to be combined The result may then be assigned to the transform property of the UIView object to be transformed The following code fragment for example both scales and rotates a UIView object named myView CGAffineTransform scaleTrans CGAffineTransformMakeScale 2 2 CGAffineTransform rotateTrans CGAffineTransformMakeRotation angle M PI 180 myView transform CGAffineTransformConcat scaleTrans rotateTrans Affine transformations offer an extremely powerful and flexible mechanism for creating animations and it is just not possible to do justice to these capabilities in a single chapter In order to learn more about affine transformations a good starting place is the Transforms chapter of Apple s Quartz 2D Programming Guide Creating the Animation Example Application The remainder of this chapter is dedicated to the creation of an iPad application intended to demonstrate the use of Core Animation The end result is a simple application on which a blue square appears When the user touches a location on the screen the box moves to that location Through the use of affine transformations the box will rotate 180 degrees as it moves to the new location whilst also changing in size Begin by launching Xcode and creating a new Single View Application with both product and class prefix named animate Implementing the Interface File For the purposes of this application we will need a UIView to represent the blue square and variables to contain the rotation angle and scale factor by which the square will be transformed These need to be declared in the animateViewController h file as follows import UIKit UIKit h interface animateViewController UIViewController property nonatomic float scaleFactor property nonatomic float angle property strong nonatomic UIView boxView end Drawing in the UIView Having declared the UIView reference we now need to initialize an instance object and draw a blue square located at a specific location on the screen We also need to initialize our scaleFactor and angle variables and add boxView as a subview of the application s main view object These tasks only need to be performed once when the application first starts up so a good option is to override the loadView method in the animateViewController m file Note that in

    Original URL path: http://www.techotopia.com/index.php/Basic_iOS_5_iPad_Animation_using_Core_Animation (2016-02-13)
    Open archived version from archive

  • Integrating iAds into an iOS 5 iPad App - Techotopia
    we will work step by step through the creation of a simple iOS 5 iPad application that includes an iAd banner view advertisement Begin this tutorial by launching Xcode and creating a new iOS iPad application project named iAdApp using the Single View Application template The ultimate goal of this example is to create an application consisting of a table view and an iAd banner view The banner will be configured to only appear when an ad is successfully downloaded from the iAds server and will change format to match the orientation of the device Adding the iAds Framework to the Xcode Project Once the new project has been created the first step is to make sure the iAds framework is included in the project Failure to add this framework will result in compilation and linking errors when building the application To add the iAds framework select the iAdApp target located at the top of the project navigator panel In the center pane select the Build Phases tab and unfold the Link Binary With Libraries panel Click on the button to display a list of existing frameworks locate and select iAd Framework and click the Add button The iAd Framework will now appear in the frameworks list along with the other frameworks already included in the project Configuring the View Controller The next step is to declare an instance of the ADBannerView class and provide an outlet to the table view object that we will be placing in our user interface file in a later step These steps are performed in the iAdAppViewController h interface file The necessary code is outlined below note also the requirement to import the iAd iAd h header file import UIKit UIKit h import iAd iAd h interface iAdAppViewController UIViewController ADBannerViewDelegate property strong nonatomic ADBannerView bannerView property strong nonatomic IBOutlet UITableView tableView end In the above code we have also added a line that reads ADBannerViewDelegate This indicates to the compiler that within the view controller we will be implementing the delegate methods for the banner view protocol Designing the User Interface The next step is to design the user interface and connect the table view object to the tableView outlet declared in the view controller interface file above Select the iAdAppViewController xib file display the Object library View Utilities Show Object Library and drag and drop a UITableView object into the View window as illustrated in Figure 50 1 Figure 50 1 Establish a connection between the table view object and the tableView outlet in the view controller by holding down the Ctrl key clicking on the File s Owner object and dragging the resulting blue line to the table view in the design panel Release the line and select the tableView outlet from the resulting menu Creating the Banner Ad For the purposes of this example we will create an instance of the ADBannerView in the viewDidLoad method of the view controller Select the iAdAppViewController m implementation file locate the method and modify

    Original URL path: http://www.techotopia.com/index.php/Integrating_iAds_into_an_iOS_5_iPad_App (2016-02-13)
    Open archived version from archive

  • An Overview of iOS 5 iPad Multitasking - Techotopia
    the background state either by design or by necessity then the applicationDidEnterBackground delegate method is triggered When a foreground application enters the background the application transitions to the inactive state triggering a call to the application delegate s applicationWillResignActive method This in turn is followed by a transition to background status which is accompanied by a call to the applicationDidEnterBackground method If the application has not indicated that it is eligible to continue running in the background the application is given 5 seconds to complete any tasks before returning from the applicationDidEnterBackground method If these tasks cannot be performed in the time given they may be performed by making a call to the beginBackgroundTaskWithExpirationHandler method followed by a call to the endBackgroundTask method when the task is complete Failure to return from the applicationDidEnterBackground method within the allocated time will result in the application being terminated When an application is moved from the background to the foreground the applicationWillEnterForeground method is triggered followed by a call to applicationDidBecomeActive Finally when an application is about to be terminated either by the user or the system the application delegate s applicationWillTerminate method is called Disabling Multitasking for an iOS Application Multitasking support is the default for all applications developed in Xcode using the iOS 4 0 SDK or later In situations where an application is required to exit rather than enter background mode a configuration setting is required in the application s Info plist file To achieve this load the project associated with the app into Xcode and select the Info plist file from the Supporting Files section of the project navigator panel In order to disable multitasking the Application does not run in background key must be added to the file with the value of YES If this key is not already listed in the file select the bottom most item in the list and click on the button to add a new key At this point a drop down menu will appear containing a list of available keys Scroll down the list to locate and select the Application does not run in background key as illustrated in Figure 51 1 Figure 51 1 Once selected set the value located in the Value column to YES Figure 51 2 Checking for Multitasking Support Multitasking is only supported on the iPhone 3GS and later devices running iOS 4 0 or newer and on all iPads In the case of devices where multitasking is not supported applications are simply terminated rather than being placed in the background If you are developing an application that relies on multitasking it is recommended that defensive code be implemented to check for multitasking support so that application behavior can be modified to compensate for the missing functionality This can be achieved using the following code fragment bool multitaskingAvailable UIDevice device UIDevice currentDevice backgroundIsSupported NO if device respondsToSelector selector isMultitaskingSupported backgroundISSupported device multitaskingSupported return backgroundIsSupported When the above method is called it returns either YES or NO depending

    Original URL path: http://www.techotopia.com/index.php/An_Overview_of_iOS_5_iPad_Multitasking (2016-02-13)
    Open archived version from archive

  • Scheduling iOS 5 iPad Local Notifications - Techotopia
    schedule the local notification must be placed In the case of this example a template method can be found in the localNotifyAppDelegate m file Within the main Xcode project navigator panel select this file and scroll down until the method comes into view void applicationDidEnterBackground UIApplication application Use this method to release shared resources save user data invalidate timers and store enough application state information to restore your application to its current state in case it is terminated later If your application supports background execution called instead of applicationWillTerminate when the user quits Adding a Sound File to the Project When a local notification is triggered the option is available to play a sound to gain the user s attention If such an audio alert is required the corresponding sound file must be added to the application project resources and must be in Linear PCM MA4 IMA ADPCM uLaw or aLaw format If no sound file is specified the default is for the notification to be silent For the purposes of this exercise we will copy an audio file from the Mac OS X system on which Xcode is running and use it when scheduling the notification To locate this file open the Finder tool and search for a file named Glass aiff AIFF being PCM format Once located drag this file and drop it onto the Supporting Files category located in the Xcode project navigator panel and click the Finish button in the resulting panel The audio file should now be included in the list of resources for the project ready to be accessed by the application code Scheduling the Local Notification Local notifications require the use of the UILocalNotification class combined with an NSDate object configured with the date and time that the notification is to be triggered Properties may also be set to specify the text to be displayed to the user an optional repeat interval and a message to be displayed to the user in the alert box With these requirements in the mind the following code creates an NSDate object based on the current date and time plus 10 seconds This date object is then used to schedule a notification with no repeats a text message and the sound from the Glass aiff file void applicationDidEnterBackground UIApplication application NSDate alertTime NSDate date dateByAddingTimeInterval 10 UIApplication app UIApplication sharedApplication UILocalNotification notifyAlarm UILocalNotification alloc init if notifyAlarm notifyAlarm fireDate alertTime notifyAlarm timeZone NSTimeZone defaultTimeZone notifyAlarm repeatInterval 0 notifyAlarm soundName Glass aiff notifyAlarm alertBody Staff meeting in 30 minutes app scheduleLocalNotification notifyAlarm Testing the Application To test the application click on the Run tool bar button located in the Xcode project window After compiling and linking the application it will load and run in the iOS Simulator Once the application has loaded into the iPad simulator click on the device home button to place the app into background mode After 10 seconds have elapsed the notification should appear accompanied by the glass sound from the audio file Figure

    Original URL path: http://www.techotopia.com/index.php/Scheduling_iOS_5_iPad_Local_Notifications (2016-02-13)
    Open archived version from archive

  • An Example iOS 5 iPad Location Application - Techotopia
    data make sure that the labels are stretched to the right until the blue margin guideline appears The data will be displayed to multiple levels of decimal points requiring space beyond the default size of the label Establish a connection between the latitude outlet declared in the view controller and the corresponding user interface label by Ctrl clicking on the File s Owner icon and dragging the blue line to the label located to the right of the Latitude label Release the line and select the latitude outlet from the resulting menu Repeat this task to establish outlet connections to the remaining six data display labels The final step of the user interface design process is to connect the button object to the resetDistance action method This is achieved by selecting the button in the view window and displaying the Connections Inspector window View Utilities Show Connections Inspector Click in the round circle to the right of the Touch Up Inside event and drag the line to the File s Owner object On releasing the mouse button select the resetDistance method from the resulting menu Creating the CLLocationManager Object The next task is to implement the code to create an instance of the CLLocationManager class Since this needs to occur when the view loads an ideal location is in the view controller s viewDidLoad method Whilst making this code change it is also a good opportunity to add the necessary synthesize directives to the locationViewController m file import locationViewController h interface locationViewController end implementation locationViewController synthesize longitude latitude horizontalAccuracy verticalAccuracy altitude distance synthesize locationManager startLocation resetButton void viewDidLoad super viewDidLoad self locationManager CLLocationManager alloc init self locationManager desiredAccuracy kCLLocationAccuracyBest self locationManager delegate self locationManager startUpdatingLocation self startLocation nil The above code creates a new CLLocationManager object instance and configures it to use the best accuracy setting It then declares itself as the application delegate for the object The location manager object is then instructed to begin updating location information via a call to the startUpdatingLocation method Since location tracking has just begun at this point the startLocation object is also set to nil Implementing the Action Method The button object in the user interface is connected to the resetDistance action method so the next task is to implement that action All this method needs to do is set the startlocation object to nil void resetDistance self startLocation nil Implementing the Application Delegate Methods When the location manager detects a location change it calls the didUpdateToLocation delegate method Since the view controller was declared as the delegate for the location manager in the viewDidLoad method it is necessary to now implement this method pragma mark pragma mark CLLocationManagerDelegate void locationManager CLLocationManager manager didUpdateToLocation CLLocation newLocation fromLocation CLLocation oldLocation NSString currentLatitude NSString alloc initWithFormat 6f newLocation coordinate latitude self latitude text currentLatitude NSString currentLongitude NSString alloc initWithFormat 6f newLocation coordinate longitude self longitude text currentLongitude NSString currentHorizontalAccuracy NSString alloc initWithFormat 6f newLocation horizontalAccuracy self horizontalAccuracy text currentHorizontalAccuracy NSString currentAltitude NSString alloc initWithFormat

    Original URL path: http://www.techotopia.com/index.php/An_Example_iOS_5_iPad_Location_Application (2016-02-13)
    Open archived version from archive

  • Accessing the iPad Camera and Photo Library - Techotopia
    property Whether or not the user is permitted to perform editing before the image is passed on to the application is controlled via the allowsEditing boolean property The following code creates a UImagePickerController instance and configures it for camera use with movie and image support and editing allowed It then displays the controller and releases the controller object UIImagePickerController imagePicker UIImagePickerController alloc init imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceTypeCamera imagePicker mediaTypes NSArray arrayWithObjects NSString kUTTypeImage NSString kUTTypeMovie nil imagePicker allowsEditing YES self presentModalViewController imagePicker animated YES It should be noted that the above code also configured the current class as the delegate for the UIImagePickerController instance This is actually a key part of how the class works and is covered in the next section Configuring the UIImagePickerController Delegate When the user is presented with the UIImagePickerController object user interface the application essentially hands control to that object That being the case the controller needs some way to notify the application that the user has taken a photo recorded a video or made a library selection It does this by calling delegate methods The class that instantiates a UIImagePickerController instance should therefore declare itself as the object s delegate conform to the UIImagePickerControllerDelegate and UINavigationControllerDelegate protocols and implement the didFinishPickingMediaWithInfo and imagePickerControllerDidCancel methods When the user has selected or created media the didFinishPickingMediaWithInfo method is called and passed an NSDictionary object containing the media and associated data In the event that the user cancels the operation the imagePickerControllerDidCancel method is called In both cases it is the responsibility of the delegate method to dismiss the view controller void imagePickerController UIImagePickerController picker didFinishPickingMediaWithInfo NSDictionary info Code here to work with media self dismissModalViewControllerAnimated YES void imagePickerControllerDidCancel UIImagePickerController picker self dismissModalViewControllerAnimated YES The info argument passed to the didFinishPickingMediaWithInfo method is an NSDictionary object containing the data relating to the image or video created or selected by the user The first step is typically to identify the type of media NSString mediaType info objectForKey UIImagePickerControllerMediaType if mediaType isEqualToString NSString kUTTypeImage Media is an image else if mediaType isEqualToString NSString kUTTypeMovie Media is a video The original unedited image selected or photographed by the user may be obtained from the info dictionary as follows UIImage image info objectForKey UIImagePickerControllerOriginalImage Assuming that editing was enabled on the image picker controller object the edited version of image may be accessed via the UImagePickerControllerEditedImage dictionary key UIImage image info objectForKey UIImagePickerControllerEditedImage If the media is a video the URL of the recorded media may be accessed as follows NSURL url info objectForKey UIImagePickerControllerMediaURL Once the image or video URL has been obtained the application can optionally save the media to the library and either display the image to the user or play the video using the MPMoviePlayer class as outlined in the chapter entitled Video Playback from within an iOS 5 iPad Application Detecting Device Capabilities Not all iOS devices provide the same functionality iPhone models prior to the 3GS model for example do not support the

    Original URL path: http://www.techotopia.com/index.php/Accessing_the_iPad_Camera_and_Photo_Library (2016-02-13)
    Open archived version from archive

  • An Example iOS 5 iPad Camera Application - Techotopia
    resulting line to the UIImageView object in the view window Select the imageView outlet from the resulting menu Repeat this step to connect the toolbar outlet to the UIToolBar component Adding another Button to the Toolbar When the toolbar was added to the view it also included a single bar button item Since the application will need two buttons drag and drop a second bar button item from the Object Library onto the toolbar Double click on the first button and change the label to Camera Repeat this step to change the second button to read Camera Roll Ctrl click over the Camera button and drag the resulting line to the File s Owner icon Release the line and select the useCamera method Similarly connect the Camera Roll button to the useCameraRoll method Implementing the Camera Action Method The useCamera method now needs to be implemented This method first needs to check that the device on which the application is running has a camera It then needs to create a UIImagePickerController instance assign the cameraViewController as the delegate for the object and define the media source as the camera Since we do not plan on handling videos the supported media types property is set to images only Finally the camera interface will be displayed The last task is to set the newMedia flag to YES to indicate that the image is new and therefore needs to be saved and is not an existing image from the camera roll Bringing all these requirements together along with the synthesize directive for the previously declared outlets gives us the following useCamera method import cameraViewController h interface cameraViewController end implementation cameraViewController synthesize imageView popoverController toolbar newMedia IBAction useCamera id sender if UIImagePickerController isSourceTypeAvailable UIImagePickerControllerSourceTypeCamera UIImagePickerController imagePicker UIImagePickerController alloc init imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceTypeCamera imagePicker mediaTypes NSArray arrayWithObjects NSString kUTTypeImage nil imagePicker allowsEditing NO self presentModalViewController imagePicker animated YES newMedia YES end Implementing the useCameraRoll Method The useCameraRoll method is responsible for displaying the camera roll view within a popover the code for which is as follows IBAction useCameraRoll id sender if self popoverController isPopoverVisible self popoverController dismissPopoverAnimated YES else if UIImagePickerController isSourceTypeAvailable UIImagePickerControllerSourceTypeSavedPhotosAlbum UIImagePickerController imagePicker UIImagePickerController alloc init imagePicker delegate self imagePicker sourceType UIImagePickerControllerSourceTypePhotoLibrary imagePicker mediaTypes NSArray arrayWithObjects NSString kUTTypeImage nil imagePicker allowsEditing NO self popoverController UIPopoverController alloc initWithContentViewController imagePicker self popoverController delegate self self popoverController presentPopoverFromBarButtonItem sender permittedArrowDirections UIPopoverArrowDirectionUp animated YES newMedia NO The code begins by checking if the popover is already displayed If so then this indicates that the user has touched the Camera Roll button a second time after the popover was displayed Convention dictates that under such circumstances the popover should be dismissed In the event that the popover is not yet visible an image picker object is created configured to display the camera roll with images only and editing disabled The popover controller is then created passing through the image picker as the view The view controller is designated as the delegate for the popover object

    Original URL path: http://www.techotopia.com/index.php/An_Example_iOS_5_iPad_Camera_Application (2016-02-13)
    Open archived version from archive



  •