制作Gif动图

//创建一个协议文件PrefixHeader_pch

ifndef MakeGif_PrefixHeader_pch

define MakeGif_PrefixHeader_pch

define ColorChangeNotification @”ColorChangeNoti”

define RepealNotification @”RepealNotification”

endif

//创建两个子类GifView和DrawView
//Gif的interface.h文件,其中#import

import

import

import “GifView.h”

import

pragma mark ———–

+(void)createGifViewWithImages:(NSArray *)sourceImages{

//创建输出路径
NSString *gifDirectory = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"gifDir"];

BOOL flag = [[NSFileManager defaultManager] fileExistsAtPath:gifDirectory];
if (!flag) {
[[NSFileManager defaultManager] createDirectoryAtPath:gifDirectory withIntermediateDirectories:YES attributes:nil error:nil];
}

NSString *gifFilePath = [gifDirectory stringByAppendingPathComponent:@"1.gif"];
NSLog(@"gifFilePath = %@",gifFilePath);


//创建gif动画
//图像目标
CGImageDestinationRef destination;
//创建CFURL对象
CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)gifFilePath, kCFURLPOSIXPathStyle, false);
//通过一个url
destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, sourceImages.count, NULL);
//设置gif信息,播放时间,基本数据和delay时间
NSDictionary *frameGifProperties = @{(NSString *)kCGImagePropertyGIFDictionary:@{(NSString *)kCGImagePropertyGIFDelayTime:@0.3}};
//设置gif信息
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:@YES forKey:(NSString *)kCGImagePropertyGIFHasGlobalColorMap];
[dictionary setObject:(NSString *)kCGImagePropertyColorModelRGB forKey:(NSString *)kCGImagePropertyColorModel];
[dictionary setObject:@8 forKey:(NSString *)kCGImagePropertyDepth];
[dictionary setObject:@0 forKey:(NSString *)kCGImagePropertyGIFLoopCount];
NSDictionary *theGifProperties = @{(NSString *)kCGImagePropertyGIFDictionary:dictionary};

//合成gif
for (int i = 0; i < sourceImages.count; i++) {
    UIImage *img = [sourceImages objectAtIndex:i];
    CGImageRef ref = img.CGImage;
    CGImageDestinationAddImage(destination, ref, (__bridge CFDictionaryRef)frameGifProperties);
}
CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)theGifProperties);
CGImageDestinationFinalize(destination);
CFRelease(destination);    

}
@end

//DrawView的头文件

import

import “DrawView.h”

@implementation DrawView
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self name:ColorChangeNotification object:nil];
}

-(id)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor whiteColor];
self.userInteractionEnabled = YES;
self.multipleTouchEnabled = YES;
self.backgroundColor = [UIColor whiteColor];
lines = [NSMutableArray array];

    //注册通知接受者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(colorChanegNotiAction:) name:ColorChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(repealNotiAction:) name:RepealNotification object:nil];

}
return self;

}

  • (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 5);

    for (int i = 0; i < lines.count; i++) {
    NSMutableArray *points = [lines[i] objectForKey:@”points”];
    UIColor *strokeColor = [[lines objectAtIndex:i] objectForKey:@”lineColor”];
    CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);
    CGContextMoveToPoint(context, [points[0] CGPointValue].x, [points[0] CGPointValue].y);

    for (int i = 1; i < points.count; i++) {
        CGContextAddLineToPoint(context, [points[i] CGPointValue].x, [points[i] CGPointValue].y);
    }
    
     CGContextStrokePath(context);
    

    }

}

-(void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event{
NSMutableArray *points = [NSMutableArray array];
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
[points addObject:[NSValue valueWithCGPoint:point]];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:points forKey:@”points”];
[dic setValue:lineColor forKey:@”lineColor”];
[lines addObject:dic];

}

-(void)touchesMoved:(NSSet )touches withEvent:(UIEvent )event{
NSMutableArray *points = [[lines lastObject] objectForKey:@”points”];
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
[points addObject:[NSValue valueWithCGPoint:point]];

[self setNeedsDisplay];//调用drawRect方法

}
-(void)touchesEnded:(NSSet )touches withEvent:(UIEvent )event{

}

pragma mark ———

-(void)colorChanegNotiAction:(NSNotification *)sender{

lineColor = [UIColor colorWithRed:[sender.userInfo[@"R"] floatValue] green:[sender.userInfo[@"G"] floatValue] blue:[sender.userInfo[@"B"] floatValue] alpha:1];

}
-(void)repealNotiAction:(NSNotification *)sender{
[lines removeLastObject];
[self setNeedsDisplay];
}
@end
//ViewController实现文件

import “ViewController.h”

import “EditViewController.h”

@interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    //导入第三方 实现毛玻璃效果

}
- (IBAction)editButtonAction:(UIButton *)sender {

EditViewController *editViewController = [[EditViewController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:editViewController];
navigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:navigationController animated:YES completion:nil];

}
- (IBAction)photoButtonAction:(id)sender {
}
- (IBAction)cameraButtonAction:(id)sender {
}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

@end
//EditViewController实现文件

import “EditViewController.h”

import “DrawView.h”

import “PlayViewController.h”

@interface EditViewController ()
{
UIScrollView *srollView;
int count;

/////
UIView *colorView;

}
@end

@implementation EditViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    count = 1;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRewind target:self action:@selector(backAction:)];
    self.title = [NSString stringWithFormat:@”图片%d”,count];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPhotoAction:)];

    [self.navigationController setToolbarHidden:NO animated:YES];
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    UIBarButtonItem *colorButtonItem = [[UIBarButtonItem alloc] initWithTitle:@”颜色” style:UIBarButtonItemStylePlain target:self action:@selector(colorAction:)];
    UIBarButtonItem *toolButtonItem = [[UIBarButtonItem alloc] initWithTitle:@”工具” style:UIBarButtonItemStylePlain target:self action:@selector(toolAction:)];
    UIBarButtonItem *clearButtonItem =[[UIBarButtonItem alloc] initWithTitle:@”清空” style:UIBarButtonItemStylePlain target:self action:@selector(clearAction:)];

    UIBarButtonItem *repealButtonItem =[[UIBarButtonItem alloc] initWithTitle:@”回删” style:UIBarButtonItemStylePlain target:self action:@selector(repealAction:)];

    UIBarButtonItem *createGifButtonItem =[[UIBarButtonItem alloc] initWithTitle:@”合成” style:UIBarButtonItemStylePlain target:self action:@selector(createGifAction:)];

    self.toolbarItems = @[spaceItem,colorButtonItem,spaceItem,toolButtonItem,spaceItem,clearButtonItem,spaceItem,repealButtonItem,spaceItem,createGifButtonItem,spaceItem];

    //图片编辑区域
    self.automaticallyAdjustsScrollViewInsets = NO;

    srollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64-44)];
    //内容大小
    srollView.contentSize = CGSizeMake(srollView.frame.size.width*count, 0);
    //偏移量
    srollView.contentOffset = CGPointMake(0, 0);

    DrawView *drawView = [[DrawView alloc] initWithFrame:srollView.bounds];
    drawView.tag = 1000+count;

    [srollView addSubview:drawView];

    srollView.pagingEnabled = YES;

    srollView.delegate = self;

    srollView.scrollEnabled = NO;

    [self.view addSubview:srollView];

    colorView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-80-44, self.view.frame.size.width, 80)];
    colorView.backgroundColor = [UIColor grayColor];
    colorView.hidden = YES;
    NSArray *texts = @[@”红色”,@”绿色”,@”蓝色”];
    for (int i = 0; i < 3; i++) {
    UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 5*i+i*20, colorView.frame.size.width-60, 20)];
    slider.tag = 100 + i;
    slider.value = 0.5;
    [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [colorView addSubview:slider];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(colorView.frame.size.width-60, 5*i+i*20, 60, 20)];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = texts[i];
    [colorView addSubview:label];
    

    }

    [self.view addSubview:colorView];

}

-(void)backAction:(UIButton *)sender{
[self dismissViewControllerAnimated:YES completion:nil];
}

-(void)addPhotoAction:(UIButton *)sender{
count++;
srollView.contentSize = CGSizeMake(srollView.frame.size.width*count, 0);
DrawView drawView = [[DrawView alloc] initWithFrame:CGRectMake(srollView.frame.size.width(count-1), 0, srollView.frame.size.width, srollView.frame.size.height)];
drawView.tag = 1000+count;
[srollView addSubview:drawView];
[srollView setContentOffset:CGPointMake(srollView.frame.size.width*(count-1), 0) animated:YES];

self.title = [NSString stringWithFormat:@"图片%d",count];

}

pragma mark —-工具栏按钮——

-(void)colorAction:(UIButton *)sender{
colorView.hidden = !colorView.hidden;
}

-(void)toolAction:(UIBarButtonItem *)sender{

}

-(void)clearAction:(UIBarButtonItem *)sender{

}
-(void)repealAction:(UIBarButtonItem *)sender{
[[NSNotificationCenter defaultCenter] postNotificationName:RepealNotification object:nil userInfo:nil];
}

-(void)createGifAction:(UIBarButtonItem *)sender{
NSMutableArray *images = [NSMutableArray array];
for (int i = 1; i <= count; i++) {
DrawView drawView = (DrawView )[self.view viewWithTag:1000+i];
UIGraphicsBeginImageContext(drawView.bounds.size);
[drawView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
[images addObject:image];
UIGraphicsEndImageContext();
}

NSLog(@"images = %@",images);
PlayViewController *playViewController = [[PlayViewController alloc] init];
playViewController.images = images;

[self presentViewController:playViewController animated:YES completion:nil];

}

pragma mark ———

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{

}

pragma mark —slider—

-(void)sliderAction:(UISlider *)sender{
NSLog(@”sliderValue = %f”,sender.value);
UISlider redSlider = (UISlider )[self.view viewWithTag:100];
UISlider greenSlider = (UISlider )[self.view viewWithTag:101];
UISlider blueSlider = (UISlider )[self.view viewWithTag:102];
[[NSNotificationCenter defaultCenter] postNotificationName:ColorChangeNotification object:nil userInfo:@{@”R”:@(redSlider.value),@”G”:@(greenSlider.value),@”B”:@(blueSlider.value)}];

}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

/*

pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/

@end
//PlayViewController的头文件

import

import “PlayViewController.h”

import “GifView.h”

@interface PlayViewController ()

@end

@implementation PlayViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    [GifView createGifViewWithImages:_images];

    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@”gifDir”];
    filePath = [filePath stringByAppendingPathComponent:@”1.gif”];

    GifView *gifView = [[GifView alloc] initWithFrame:CGRectMake(100, 100, 100, 100) FilePath:filePath];
    [self.view addSubview:gifView];

    for (int i = 0; i < gifView.images.count; i++) {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0+i*60, 300, 60, 80)];
    imageView.image = gifView.images[i];
    [self.view addSubview:imageView];
    }

}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

/*

pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/

@end

你可能感兴趣的:(UI的学习)