IOS UI Image and Drawing

Posted by faraway on Tue, 23 Jul 2019 10:23:27 +0200

Articles Catalogue


For example, we need to add watermarking to the picture, and we need to cut and process the picture in drawing. All of these are specific operations in drawing.

Drawing pictures

UIImage class

The method of creating UIImage object is provided in UIImage class, which includes class method and instance method. The most commonly used methods are as follows:

imageNamed: Class method that reads image files from the main bundle. Usually, the image is placed in the Assets.xcassets folder of the project, and the UIImage object can be created as long as the file name is provided.

+(nullable UIImage *)imageNamed:(NSString *)name;

Image WithContentOfFile: Class method, which reads pictures from engineering files, passes in a picture path parameter, and finally obtains a UIImage object.

+(nullable UIImage *)imageWithContentsOfFile:(NSString *)path;

imageWithData: Class method that loads images from an NSData object;

+(nullable UIImage *)imageWithData:(NSData *)data;

initWithContentsOfFile: Instance method, similar to imageWithContentOfFile, requires the path to the image.

-(nullable instancetype)initWithContentsOfFile:(NSString *)path;

The following example code demonstrates common methods for creating UIImage objects.

UIImage *image1 = [UIImage imageNamed:@"logo"];
NSString *path = [[NSBundle mainBundle] pathForResource:@"99ios" ofType:@"png"];
UIImage *image2 = [UIImage imageWithContentsOfFile:path];

Drawing method

In the UIImage class, two main drawing methods are provided, which can draw pictures into the drawing context (some are similar to stamping after painting, which can display a complete stamp figure on paper with only one stamp, which is different from drawing with a pen):

DraAtPoint: Take the upper left corner of the picture as the anchor point, and display it at the designated Point position. The original size of the picture is displayed without compression.

-(void)drawAtPoint:(CGPoint)point;

DraInRect: Place the picture in a rectangular area and it will probably zoom in/out or stretch/compress.

-(void)drawInRect:(CGRect)rect; 

Use

Later drawings will cover up the first drawings.
Create a class named MainView, inherited from UIView, and in StoryBoard, modify the main controller View type to MainView.

//  MainView.m
//  UI Image and Drawing
//
//  Created by  on 2019/7/22.
//  Copyright © 2019 Shae. All rights reserved.
//

#import "MainView.h"

@implementation MainView

- (void)drawRect:(CGRect)rect{
    UIImage *image1=[UIImage imageNamed:@"1"];
    NSString *path=[[NSBundle mainBundle] pathForResource: @"2"ofType:@"jpg"];
    UIImage *imgae2=[UIImage imageWithContentsOfFile:path];
    
    //Draw image1 first
    [image1  drawAtPoint:CGPointZero];
    
    //Drawing imgae2
    [imgae2 drawInRect:CGRectMake(0, 250, 100, 100)];
}

@end

Watermarking

In applications like Sina Weibo, watermarking is automatically added to uploaded pictures, and watermarking is also achieved by drawing, that is, first painting pictures on canvas, and then adding watermarking signatures.
The functions provided in the UIGraphics class are often used to modify and process UIImage objects. Modifying UIImage objects usually takes the following steps:

  • Call the UIGraphics BeginImageContext method to open a blank image context, which contains the parameters and attributes of the drawing, that is, a canvas and a drawing environment.
UIKIT_EXTERN void     UIGraphicsBeginImageContext(CGSize size);
UIKIT_EXTERN void     UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
  • Draw the content in this context, such as adding pictures, adding text, etc.
  • According to the content of the latest image context, we call the UIGraphics GetImageFromCurrent ImageContext function to get a UIImage object after image synthesis.
UIKIT_EXTERN UIImage* __null_unspecified UIGraphicsGetImageFromCurrentImageContext(void);
  • Call the UIGraphics EndImageContext function to close the context to save memory.
UIKIT_EXTERN void     UIGraphicsEndImageContext(void); 

Use

The way to classify is to add watermarking functions to UIImage

Classification.h

//
//  UIImage+MYImage.h
//  UI Image and Drawing
//
//  Created by  on 2019/7/22.
//  Copyright © 2019 Shae. All rights reserved.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIImage (MYImage)
+(UIImage *) image:(UIImage *)image addWaterMarkWithString:(NSString *)string;
@end

NS_ASSUME_NONNULL_END

Classification.m

//
//  UIImage+MYImage.m
//  UI Image and Drawing
//
//  Created by  on 2019/7/22.
//  Copyright © 2019 Shae. All rights reserved.
//

#import "UIImage+MYImage.h"

@implementation UIImage (MYImage)
+ (UIImage *)image:(UIImage *)image addWaterMarkWithString:(NSString *)string{
    //Open a graphical context
    UIGraphicsBeginImageContext(image.size);
    //Drawing context: 1. Drawing pictures
    [image drawAtPoint:CGPointMake(0, 20)];
    //Drawing context: 2. Add text to context
    NSDictionary *dict=@{NSFontAttributeName:[UIFont systemFontOfSize:80.0],
                         NSForegroundColorAttributeName:[UIColor blackColor]
                         };
    [string drawAtPoint:CGPointMake(60, 60) withAttributes:dict];
    //Getting composite images from the graphics context
    UIImage *watermarkImage=UIGraphicsGetImageFromCurrentImageContext();
    //Close the context
    UIGraphicsEndImageContext();
    return watermarkImage;
    
}
@end

Use classification

-(void)addWaterMark{
    UIImage *image1=[UIImage imageNamed:@"1"];
    UIImage *imageWater =[UIImage image:image1 addWaterMarkWithString:@"Shae"];
    UIImageView *imageView=[[UIImageView alloc]initWithImage:imageWater];
    imageView.frame=CGRectMake(0, 0, 1025, 576);
    [self addSubview:imageView];
}

Code 1:

https://github.com/ShaeZhuJiu/UIImgaeAndDraw_1.git

Cut out circular pictures

For example, cut a square image into a circle, such as a personal head.

Clipping by drawing

When using the drawing method to cut the picture, the main idea is to cut out a circular graphics context, which is equivalent to get a circular canvas, and then draw on the circular canvas, and naturally get a circular picture.

The following example code implements clipping a square image and eventually a circular image.

-(UIImage *)clipImageView:(UIImage *)image{
    //Open context
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);
    //  Getting Path
    UIBezierPath *path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    //Cut round
    [path addClip];
    //n Put pictures in context
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    //Save new pictures
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    //Close the context
    UIGraphicsEndImageContext();
    return  newImage;
    
}
//
//  ViewController.m
//  UIImageLipe
//
//  Created by Xie Xin on 2019/7/23.
//  Copyright © 2019 Shae. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *clipImageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage *image=[UIImage imageNamed:@"2"];
    UIImage *newImage=[self clipImageView:image];
    _clipImageView.image=newImage;
   
}

Other methods

In the actual development process, there is a more common and simple way to achieve the clipping of picture control, that is, modifying the layer attribute of UIView.

There is a CALayer attribute in UIView class, layer, which can also be clipped by modifying layer.

There are two commonly used attributes in the CALayer class, cornerRadius and masksToBounds attributes

@property CGFloat cornerRadius;//Rounded radius
@property BOOL masksToBounds; //Whether or not to tailor
-(void)clipImageView2{
UIImage *image=[UIImage imageNamed:@"2"];
_clipImageView.image=image;
_clipImageView.layer.cornerRadius=_clipImageView.bounds.size.width*0.5;
_clipImageView.layer.masksToBounds=YES;
}

Screen capture

In game applications, screenshots are usually provided to record brilliant game records. The UIKit framework also provides a simple and efficient screenshot method, as well as a way to save screenshot files for developers to call directly.
Usually, there are two steps to add screenshots to an application:

The first step is to get the current screen capture image. In the UIView class, the drawViewHierarchyInRect: afterScreenUpdates method is provided, which can be used to intercept any View image. Before use, you need to prepare the drawing context in advance.

- (BOOL)drawViewHierarchyInRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates ;

The second step is to save the picture to the local album. In the UIImagePickerController class, a function UIImageWriteToSavedPhotosAlbum is encapsulated to save images to albums. Through this function, the UIImage image object can be stored in the mobile phone album.

UIKIT_EXTERN void UIImageWriteToSavedPhotosAlbum(UIImage *image, __nullable id completionTarget, __nullable SEL completionSelector, void * __nullable contextInfo) ;

Use

-(void)myScreenShot{
    //Open a graphical context
    UIGraphicsBeginImageContext(self.view.bounds.size);
    //Screen capture
    if([self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES]){
        NSLog(@"Successfully draw the screenshot.");
    }else{
         NSLog(@"Failed to draw the screenshot.");
    }
    //Get the current d context
    UIImage *screenShot= UIGraphicsGetImageFromCurrentImageContext();
    //Close the context
    UIGraphicsEndImageContext();
    //Save to album
    UIImageWriteToSavedPhotosAlbum(screenShot, self, nil, nil);
}

Crash problem of error-reporting permission to save pictures:


Solve:
1. Find the info.plist file in the project, right-click to open it as Source Code
2. Add the key-value pairs in the error message. Here we take PhotoLibrary as an example.

<key>NSPhotoLibraryAddUsageDescription</key>
    <string> This App requires your consent to read the media database </string>.



Code 2

https://github.com/ShaeZhuJiu/UIImageClip.git

Topics: github git Attribute Mobile