iOS开发-------涂鸦板(UIBezierPath 贝赛尔曲线)与 MVC初尝试

iOS 图片编辑——涂鸦——随手指移动随意画线 iOS 涂鸦 我们已经讲过画直线 和画带箭头的线段 参考:http://blog.csdn.net/lwjok2007/article/details/50885376 这节 我们尝试做一下 随意画 手指移动到哪里就在哪里画线 如下图所示: 使用Xcode创建项目,起名:TestFingerLine  (详细的创建方法 参照 http://blog.csdn.net/ 阅读详情

         涂鸦板,顾名思义就是能够在上面画点东西,贝赛尔曲线(UIBezierPath),也可以叫做贝赛尔路径。因为path的直译就是路径,看起来很高大上,之前楼主也确实这么认为的,很高大上,细细了解,其实也不难,毕竟难的东西苹果都给我们封装好了。初次用MVC模式来些iOS的东西,错误难免,请包涵,首先来看一下效果吧


首先写一点测试的字,楼主写字不好看,如图一, 然后点击两下撤销,那么如图二, 然后点击恢复一下,如图三,当点击clear的时候,全屏就清除了。




如果想用MVC,逻辑很重要,首先来屡屡逻辑


ViewController的直系下属:

LineManager:完成对基础模型Line的管理,负责Line的增删改

TouchEvents:一个响应触摸的View,捕捉触摸点,汇报给VC,让LineManager为线添加轨迹点

RenderView:只接触是没用的,还需要显示的,根据LineManager汇报的Line的数组来绘制轨迹

ButtonView:下面的按钮是掌管按钮功能的,通过汇报VC点击按钮tag值,让LineManager进行相应的操作

SettingManager:负责记录修改后的相关属性,并只在VC中进行读取操作


MySettingViewController的直系下属

SettingView:负责响应修改的相应,反馈给SettingVC,并将数据存到SettingManager中

SettingManager:完成记录修改后的数据


Line


首先完成模型,Line,能够想到的属性如下

//
//  Line.h
//  涂鸦板
//
//  Created by YueWen on 15/9/24.
//  Copyright (c) 2015年 YueWen. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface Line : NSObject

/**
 *  线的颜色
 *  默认是红色
 */
@property(nonatomic,strong)UIColor * lineColor;

/**
 *  线的宽度
 *  默认宽度是2.0
 */
@property(nonatomic,assign)NSInteger width;

/**
 *  存储路径点的数组,不能随意修改,所以设置为readOnly
 */
@property(nonatomic,strong,readonly)NSArray * points;

/**
 *  贝赛尔曲线
 */
@property(nonatomic,strong,readonly)UIBezierPath * path;

/**
 *  添加点
 *
 *  @param point 添加的点
 */
-(void)addPoint:(CGPoint)point;

@end


既然如此,在Line.m中,需要一个可变数组来增加线的点

/**
 *  延展中点的数组
 */
@property(nonatomic,strong)NSMutableArray * mPoints;

实现相关的方法

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        //初始化数组
        self.mPoints = [NSMutableArray array];
        
        //默认为红色
        self.lineColor = [UIColor redColor];
        
        //默认大小为2.0
        self.width = 2.0;
    }
    return self;
}


/**
 *  为线中添加点
 *
 *  @param point 添加的点
 */
-(void)addPoint:(CGPoint)point
{
    //转成NSValue类型的对象
    NSValue * value = [NSValue valueWithCGPoint:point];
    
    //添加到数组
    [self.mPoints addObject:value];
}


/**
 *  重写点数组的get方法
 *
 *  @return 返回点的数组
 */
-(NSArray *)points
{
    return [NSArray arrayWithArray:self.mPoints];
}


/**
 *  重写 贝赛尔曲线的get方法
 *
 *  @return 返回线的贝赛尔曲线
 */
-(UIBezierPath *)path
{
    
    //创建一个贝赛尔曲线
    UIBezierPath * pathTemp = [UIBezierPath bezierPath];
    
    //首先移动到第一个点
    [pathTemp moveToPoint:[self.mPoints[0] CGPointValue]];
    
    for (int i = 1 ;i < self.mPoints.count; i++)
    {
        //转成普通的点
        CGPoint point = [self.mPoints[i] CGPointValue];
        
        //贝赛尔曲线添加点
        [pathTemp addLineToPoint:point];
    }
    return pathTemp;
}

TouchEventsView

touchEventsView主要负责汇报触摸的点,所以比较简单,首先定义三个Block代码块,分别负责传出开始触摸的点,移动中的点,手指离开屏幕的点
typedef void(^TouchBeginEventsBlock)(CGPoint point);
typedef void(^TouchMoveEventsBlock)(CGPoint point);
typedef void(^TouchEndEventsBlock)(CGPoint point);

在touchEventsView.m的文件中,依旧声明三个属性,并在头文件中声明三个赋值方法(当然还可以在头文件中声明属性,直接赋值)
/*声明block的赋值方法*/
-(void)touchBeginEventsBlockHandle:(TouchBeginEventsBlock)b;

-(void)touchMoveEventsBlockHandle:(TouchMoveEventsBlock)b;

-(void)touchEndEventsBlockHandle:(TouchEndEventsBlock)b;

延展的属性声明
@property(nonatomic,strong)TouchBeginEventsBlock  touchBeginEvents;
@property(nonatomic,strong)TouchMoveEventsBlock touchMoveEvents;
@property(nonatomic,strong)TouchEndEventsBlock  touchEndEvents;

实现赋值方法
-(void)touchBeginEventsBlockHandle:(TouchBeginEventsBlock)b
{
    self.touchBeginEvents = b;
}

-(void)touchMoveEventsBlockHandle:(TouchMoveEventsBlock)b
{
    self.touchMoveEvents = b;
}

-(void)touchEndEventsBlockHandle:(TouchEndEventsBlock)b
{
    self.touchEndEvents = b;
}

最后实现的方法就是触摸事件,只要是继承与UIView的类都可以实现方法
//开始触摸
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //捕获点
    CGPoint point = [[touches anyObject] locationInView:self];
    
    //运行代码块,通知VC
    if (self.touchBeginEvents)
    {
        self.touchBeginEvents(point);
    }
}

//滑动的时候
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    //捕获点
    CGPoint point = [[touches anyObject] locationInView:self];
    
    //运行代码块,通知VC
    if (self.touchMoveEvents)
    {
        self.touchMoveEvents(point);
    }
    
}

//滑动结束,即手离开屏幕时
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    //捕获点
    CGPoint point = [[touches anyObject] locationInView:self];
    
    //运行代码块,通知VC
    if (self.touchEndEvents)
    {
        self.touchEndEvents(point);
    }
 
}

//功能被抢的时候
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    //捕获点
    CGPoint point = [[touches anyObject] locationInView:self];
 
    //运行代码块,通知VC
    if (self.touchEndEvents)
    {
        self.touchEndEvents(point);
    }
    
}

RenderView

      renderView只负责绘图功能,自然属性中只需要一个存储线的数组,每次划线的时候,根据每个对象里面的贝赛尔曲线(UIBezierPath)来绘制,因为存储线的数组是在延展中声明的,所以头文件中声明一个赋值的方法
/**
 *  设置线的数组
 *
 *  @param array 参数线的数组
 */
-(void)setRenderLines:(NSArray *)array;

RenderView的init方法不再给出,别忘记给数组初始化即可,下面是数组的set方法
/**
 *  设置线的数组
 *
 *  @param array 参数line数组
 */
-(void)setRenderLines:(NSArray *)array
{
    self.lines = array;
    
    //相当于系统调用drawRect的绘制方法,不能手动调用,手动调用会出现卡屏
    [self setNeedsDisplay];
}

由于数组中存储的都是Line对象,需要的UIBezierPath(贝赛尔曲线)都存在Line对象中,所以需要遍历绘制
//绘制方法只能在该方法下进行,在此方法中提供了一个绘画的环境
- (void)drawRect:(CGRect)rect
{
    
    for (Line * line in self.lines)
    {
        UIBezierPath * path = line.path;
    
        //设置宽度
        path.lineWidth = line.width;
    
        //设置颜色
        [line.lineColor setStroke];
        
        //根据贝赛尔曲线进行绘图
        [path stroke];
    }
    
}



LineManager

LineManager负责汇报给VC 他所存的线,所以需要一个回调,楼主比较熟悉Block回调,所以选择Block,方法不为一
typedef void(^lineManagerDidChangeBlock)(NSArray * lines);

既然可以对线进行保存删除,必然需要一个可变数组来存数,用延展定义相关的属性
@property(nonatomic,strong)NSMutableArray * linesArray;//存储需要绘制的线
@property(nonatomic,strong)NSMutableArray * deleteLinesArray;//存储不需要绘制的线
@property(nonatomic,strong)lineManagerDidChangeBlock lineManagerDidChange;//回调的代码块


既然是单例必然声明创建单例的方法,习惯以share开头
/**
 *  单例方法
 *
 *  @return 返回单例
 */
+(instancetype)shareLineMangaer;

实现方法如下,但不要忘记在init方法里初始化可变数组
+(instancetype)shareLineMangaer
{
    static LineManager * lineManager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        lineManager = [[LineManager alloc]init];
    });
    
    return lineManager;
}


当前面的开始触碰时,需要lineManager重新创建一条线,并且将点赋值给贝塞尔曲线的首点,需要在.h中声明,这里只给出实现方法
/**
 *  新添加一条线,并初始化
 *
 *  @param point 起始点
 *  @param color 线的颜色
 *  @param width 线的宽度
 */
-(void)addPointWithStartEvents:(CGPoint)point WithColor:(UIColor *)color Width:(NSInteger)width
{
    //创建一条线
    Line * line = [[Line alloc]init];
    
    //设置属性
    [line addPoint:point];
    line.lineColor = color;
    line.width = width;
    
    //添加到数组
    [self.linesArray addObject:line];
    
    //运行代码块通知VC
    if (self.lineManagerDidChange)
    {
        self.lineManagerDidChange(self.linesArray);
    }
    
}

在移动过程中以及结束后,需要不断地往最后一个Line里添加获取到的点
/**
 *  为最后一次的线更新点
 *
 *  @param point 参数点
 */
-(void)addPointForLastLine:(CGPoint)point
{
    //获取最后一条线
    Line * line = [self.linesArray lastObject];
    
    //增加点
    [line addPoint:point];
    
    //运行代码块,通知VC
    if (self.lineManagerDidChange)
    {
        self.lineManagerDidChange(self.linesArray);
    }
}


      撤销键的点击,从表面看是删除了一条线,但实际不是,而是从需要渲染的Line数组中取出最后一条线,放到暂时保存的数组中,相当于一个栈的操作,就是一个出栈与入栈的过程,因为两者相似,只给出一段即可
/**
 *  删除前一根线
 */
-(void)beforeButtonToDeleteLine
{
    //如果线数组中的线存在线
    if (self.linesArray.count > 0)
    {
        //取出最后一根线
        Line * line = [self.linesArray lastObject];
        
        //缓存数组中添加
        [self.deleteLinesArray addObject:line];
        
        //从线数组中删除线
        [self.linesArray removeLastObject];
        
        //返回修改后的数组
        if (self.lineManagerDidChange)
        {
            self.lineManagerDidChange(self.linesArray);
        }
       
    }

}

清除按钮最简单,只需要清空两个数组的元素即可
/**
 *  删除所有储存的线
 */
-(void)clearButtonToRemoveLine
{
    //清空数组
    [self.linesArray removeAllObjects];
    [self.deleteLinesArray removeAllObjects];
    
    //返回修改后的数组
    if (self.lineManagerDidChange)
    {
        self.lineManagerDidChange(self.linesArray);
    }
    
}

最后是根据button传入的tag值进行相应的操作,rag值传入的回调在下面的ButtonView中提到
-(void)lineManagerDidChangeWithTag:(NSInteger)tag
{
    //根据tag值进行相应的操作
    switch (tag) {
        case 0://撤销键
            [self beforeButtonToDeleteLine];
            break;
        case 1://恢复键
            [self nextButtonToRecoveryLine];
            break;
        case 2://清除键
            [self clearButtonToRemoveLine];
            break;
        default:
            break;
    }
}



ButtonView

buttonView就是一个防止按钮的小View,因为它简单,没有用xib或者storyboard来写,所以是一个纯代码的小视图

首先要有一个返回button的tag值的回调
typedef void(^buttonPressedInButtonViewBlock)(NSInteger buttonTag);

自然需要在.m中的延展中定义一个代码块的属性以及set方法,这里不再赘余

首先定义一下属性
@property(nonatomic,strong)UIButton * beforeButton;//返回先一步,消除一条线
@property(nonatomic,strong)UIButton * nextButton;//撤销前一步
@property(nonatomic,strong)UIButton * clearButton;//清除所有的线

@property(nonatomic,strong)buttonPressedInButtonViewBlock buttonPressedBlock;

初始化两个方法
-(void)awakeFromNib//从xib中实例化的时候才走
{
    [self myInitView];
}



-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self myInitView];
    }
    return self;
}

实现自己写的初始化方法myInitView
-(void)myInitView
{
    //初始化按钮属性
    self.beforeButton = [self myButtonInitWithTitle:@"撤销" Tag:0];
    self.nextButton = [self myButtonInitWithTitle:@"恢复" Tag:1];
    self.clearButton = [self myButtonInitWithTitle:@"清除" Tag:2];
    
    //添加组件
    [self addSubview:self.beforeButton];
    [self addSubview:self.nextButton];
    [self addSubview:self.clearButton];
    
    //设置背景颜色
    self.backgroundColor = [UIColor whiteColor];
    
    //为按钮进行布局
    [self myLayoutConstrains];

}


楼主依旧比较懒,所以自定义一个button的初始化方法
/**
 *  自定义按钮初始化
 *
 *  @param title 按钮上的文字
 *  @param tag   按钮的tag值
 *
 *  @return 初始化按钮的地址
 */
-(UIButton *)myButtonInitWithTitle:(NSString *)title Tag:(NSInteger)tag
{
    //初始化按钮,系统类型的
    UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    //设置tag值
    button.tag = tag;
    
    //设置按钮上的文字
    [button setTitle:title forState:UIControlStateNormal];
    
    //取消按钮的自动布局
    button.translatesAutoresizingMaskIntoConstraints = NO;
    
    //确定button的目标动作回调
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    
    //返回创建好按钮的地址
    return button;
}


手动布局的代码如下,用的字符串进行的布局
/**
 *  开始布局
 */
-(void)myLayoutConstrains
{
    //设置水平布局
    NSArray * buttonHorizatal = [NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-[_beforeButton]-[_nextButton(==_beforeButton)]-[_clearButton(==_beforeButton)]-|"] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_beforeButton,_nextButton,_clearButton)];
    [self addConstraints:buttonHorizatal];
    
    //设置垂直布局
    NSArray * buttonVerital1 = [NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-7-[_beforeButton(30)]-7-|"] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_beforeButton)];
    [self addConstraints:buttonVerital1];
    
    NSArray * buttonVerital2 = [NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-7-[_nextButton(30)]-7-|"] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_nextButton)];
    [self addConstraints:buttonVerital2];
    
    NSArray * buttonVerital3 = [NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-7-[_clearButton(30)]-7-|"] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_clearButton)];
    [self addConstraints:buttonVerital3];
}

最后就是按钮点击进行的回调方法
/**
 *  按钮被点击
 *
 *  @param button 进行目标动作回调的按钮
 */
-(void)buttonPressed:(UIButton *)button
{
    //自身的回调存在
    if (self.buttonPressedBlock)
    {
        //返回按钮的tag值
        self.buttonPressedBlock(button.tag);
    }
}


SettingView

settingView是掌管设置的页面,因为说道MySettingManager必须需要settingView,所以先介绍settingView,这个比较复杂布局,所以用的xib进行的布局,如下


     首先汇报肯定少不了回调方法,楼主依旧选择用Block回调,当然方法肯定不唯一,定义两个block,一个返回颜色,一个返回线宽,延展中的属性定义以及set方法依旧不赘余。
typedef void(^settingViewChangeColorBlock)(UIColor * lineColor);

typedef void(^settingViewChangeLineWidthChangeBlock)(CGFloat lineWidth);


接下来是当颜色的Slider发生变化时产生的回调方法
/**
 *  颜色调节器发生变化的回调
 *
 *  @param sender 调节器的发送者
 */
- (IBAction)colorSliderChanged:(id)sender
{
    //根据 三原色 以及 透明度 创建Color对象
    UIColor * lineColor = [UIColor colorWithRed:(self.redColorSlider.value / 255) green:(self.greenColorSlider.value / 255) blue:(self.blueColorSlider.value / 255) alpha:1];
    
    //改变预览label的颜色
    self.colorText.textColor = lineColor;
    
    //如果代码块存在
    if (self.colorChangeBlock)
    {
        self.colorChangeBlock(lineColor);
    }
}

然后是线宽发生变化时产生的回调
/**
 *  线的宽度调节器发生变化的回调
 *
 *  @param sender 调节器的发送者
 */
- (IBAction)lineWidthsliderChanged:(id)sender
{
    
    //获取 线的宽度
    CGFloat lineWidth = self.lineWidthSlider.value;
    
    //如果代码块存在
    if (self.lineWidthChangeBlock)
    {
        self.lineWidthChangeBlock(lineWidth);
    }
}

settingView就是这么多,依旧很简单

MySettingManager

      mySettingManager是一个存储修改后的线的颜色以及线宽的一个单例,既然是单例自然少不了单例方法,依旧习惯用share开头,只给出实现方法,不要忘记头文件中声明相关属性以及声明方法
//不允许外界修改,所以用readOnly,只能通过相应的方法设置
@property(nonatomic,strong,readonly)UIColor * lineColor;

@property(nonatomic,assign,readonly)CGFloat lineWidth;

接下来是单例的实现,以上两个属性不要忘记在init里面初始化
+(instancetype)shareSettingManager
{
    static SettingManager * settingManager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        settingManager = [[SettingManager alloc]init];
        
    });
    
    return settingManager;
}

接下来就是当颜色以及线宽发生变化时进行相应的赋值了,如下
-(void)settingManagerSetColor:(UIColor *)lineColor withLineWidth:(CGFloat)lineWidth
{
    //如果存在颜色
    if (lineColor)
    {
       _lineColor = lineColor;
        
    }
    
    //如果存在线宽
    if (lineWidth > 0)
    {
        _lineWidth = lineWidth;
    }
   
}

ViewController

viewController既为主页面的控制器,属性如下,前面都已经细解释了各个属性,因此不注释了
@property(nonatomic,strong)TouchEventsView * touchEventsView;

@property(nonatomic,strong)RenderView * renderView;

@property(nonatomic,strong)LineManager * lineManager;

@property(nonatomic,strong)SettingManager * settingManager;

@property(nonatomic,strong)ButtonView * buttonView;


接下来就是看起来比较繁琐的viewDidLoad方法了,其实就是一堆设置回调的过程,会比较长,不过有注释,可以慢慢研究
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化线的管理者
    self.lineManager = [LineManager shareLineMangaer];
    
    //初始化设置管理者
    self.settingManager = [SettingManager shareSettingManager];
    
    //初始化触碰view
    self.touchEventsView = [[TouchEventsView alloc]initWithFrame:touchFrame];

    //初始化绘图view
    self.renderView = [[RenderView alloc]initWithFrame:touchFrame];
    
    //初始化按钮view
    self.buttonView = [[ButtonView alloc]initWithFrame:CGRectMake(0, self.touchEventsView.frame.size.height, self.view.frame.size.width, 44)];
    
    //配置导航栏的相关组件
    [self otherSetting];
    
    //避免强引用循环
    __weak __block ViewController * copy_self = self;
    
    //当开始触摸屏幕的时候
    [self.touchEventsView touchBeginEventsBlockHandle:^(CGPoint point) {
    
        //管理者创建线并且添加点为起始点
        [copy_self.lineManager addPointWithStartEvents:point WithColor:copy_self.settingManager.lineColor  Width:copy_self.settingManager.lineWidth];
        
    }];
    
    //手在触摸屏上移动的时候
    [self.touchEventsView touchMoveEventsBlockHandle:^(CGPoint point) {
       
        //管理者为最后一个线更新点
        [copy_self.lineManager addPointForLastLine:point];
        
    }];
    
    //手离开触摸屏的时候
    [self.touchEventsView touchEndEventsBlockHandle:^(CGPoint point) {
       
        //管理者为最后一个线更新点
        [copy_self.lineManager addPointForLastLine:point];
        
    }];
    
    //线的数组发生变化时
    [self.lineManager lineManagerDidChangeBlockHandle:^(NSArray *lines) {
       
        //渲染视图绘制
        [copy_self.renderView setRenderLines:lines];
        
    }];
    
    //buttonView被点击
    [self.buttonView buttonPressedBlockHandle:^(NSInteger buttonTag) {
       
        //管理者根据不同的tag值执行相应的操作
        [copy_self.lineManager lineManagerDidChangeWithTag:buttonTag];
    }];
    
    
    //设置背景颜色
    self.touchEventsView.backgroundColor = [UIColor whiteColor];
    self.renderView.backgroundColor = [UIColor clearColor];
    
    //添加
    [self.view addSubview:self.buttonView];
    [self.view addSubview:self.touchEventsView];
    [self.touchEventsView addSubview:self.renderView];
  
}

因为是在navigationController进行的跳转,所以添加两个itembarbutton,能够进行相应的操作
/**
 *  配置导航栏的相关组件
 */
-(void)otherSetting
{
    //添加左右两个tabBarbutton
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(toSavePicture)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"设置" style:UIBarButtonItemStyleDone target:self action:@selector(toSettingViewContoller)];
}

设置按钮的回调方法如下
/**
 *  跳转页面的回调方法
 */
-(void)toSettingViewContoller
{
    //创建settingViewController对象
    MySettingViewController * mySettingViewController = [[MySettingViewController alloc]init];
    
    //跳转
    [self.navigationController pushViewController:mySettingViewController animated:YES];
    
}

保存按钮的回调方法如下
/**
 *  保存当前图片(截屏)
 */
-(void)toSavePicture
{
    //创建一个基于位图的图形上下文并指定大小
    UIGraphicsBeginImageContext(self.renderView.bounds.size);
    
    //renderIncontext呈现接受者以及其子范围到指定的上下文
    [self.renderView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    //返回一个基于当前图形上的上下文图片
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    
    //移除栈定基于当前位图的图形上下文
    UIGraphicsEndImageContext();
    
    //将图片保存到图片库
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}

看一下保存的结果吧

画一张测试图,点击保存后,去相册中看




MySettingController

mySettingController是设置页面的控制器,所以理论和上面的控制器逻辑是一样的,而且更为简单,因为只负责显示设置View的功能,以下是viewDidLoad的方法
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取单例
    self.settingManager = [SettingManager shareSettingManager];
    
    //初始化setting对象
    self.settingView = [[[NSBundle mainBundle] loadNibNamed:@"SettingView" owner:nil options:nil] lastObject];
    
    //设置frame
    self.settingView.frame = self.view.frame;
    
    
    //避免强引用循环
    __block __weak MySettingViewController * copy_self = self;
    
    
    
    //如果颜色调色器发生变化
    [self.settingView settingViewChangeColorBlockHandle:^(UIColor *lineColor)
    {
        //为设置管理者设置颜色
        [copy_self.settingManager settingManagerSetColor:lineColor withLineWidth:-1];

        
    }];
    
    //如果线宽调节器发生变化
    [self.settingView settingViewChangeLineWidthBlock:^(CGFloat lineWidth) {
       
        //为设置管理者设置线宽
        [copy_self.settingManager settingManagerSetColor:nil withLineWidth:lineWidth];
    }];
    
    //添加组件
    [self.view addSubview:self.settingView];
    
}

AppDelegate

因为全程没有使用storyboard,所以需要在appDelegate中设置相关的属性,方法如下,很简单
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //设置根window
    UIWindow * window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window = window;
    
    //初始化一个画板Controller
    ViewController * viewController = [[ViewController alloc]init];
    viewController.navigationItem.title = @"涂鸦板";
    
    //初始化一个navigationController
    UINavigationController * navigationController = [[UINavigationController alloc]initWithRootViewController:viewController];
    
    //设置根视图
    self.window.rootViewController = navigationController;
    
    [self.window makeKeyAndVisible];
    
    
    return YES;
}


至此,涂鸦板基本完成,好好享受自己的涂鸦板吧



iOS 图片编辑——涂鸦——在图片上添加文字 前面几节讲了图片上画线 这一节 我们简单讲一讲 给图片上添加文字的方法 我们继续使用上节的代码(代码下载地址见上节末尾   http://blog.csdn.net/lwjok2007/article/details/50887396) 首先我们将添加文字的View单独抽象出现实现 创建一个类 继承自UIView 起名: AddText 定义一个协议 当输入完成之后 将内 阅读详情

相关推荐

iOS贝塞尔曲线,折线,曲线,波浪线

可用于绘制走势图,折线图,图表类制作.

编程实现三次bezier曲线的绘制_Vue + Canvas 实现流畅的钢笔涂鸦效果

疫情期间,小朋友们都采用远程教育的方式,其中有项涂鸦的功能,看着那不流畅的画笔,就有点怪难受的,就想着自己鼓捣一下。动手前,我曾考虑采用类似 Konva 这样的三方类库,但结合自身的需求,说不定后续会有更多的个性化需求呢,综合评定后还是选择了徒手撸 Canvas 来实现,要定制 Konva 等三方类库又麻烦,还是用 Canvas 从零开始吧。准备开始前,我去体验了谷歌的涂鸦白板,Apache 的 ...

weixin_39912984的博客 872

iOS 涂鸦板 (实现切换画笔颜色,画笔粗细,可清除保存涂鸦)

iOS涂鸦板可实现基本涂鸦板功能,包括更改画笔颜色,更还画笔粗细,可实现涂鸦的前进和后退,可清除涂鸦以及保存涂鸦

iOS开发——高级篇——iOS涂鸦画板效果实现

一个简单的绘图应用,模仿苹果自带软件备忘录里的涂鸦功能 核心代码 #import "DrawView.h" #import "DrawPath.h" @interface DrawView () @property (nonatomic, strong) NSMutableArray *paths; @property (nonatomic, strong)...

weixin_30488085的博客 919

ios-iOS实现画板功能,有趣的涂鸦工具,已封装,简单快捷使用.zip

iOS实现画板功能,有趣的涂鸦工具,已封装,简单快捷使用 贝塞尔实现 源码下载:https://github.com/TangledHusky/TestOC 源码我没单独列出来,都在我的测试demo里。

IOS 贝塞尔曲线(UIBezierPath)属性、方法整理

IOS 贝塞尔曲线详解         开发IOS的朋友都知道IOS 贝塞尔曲线的重要性,由于经常会用到这样的东西,索性抽时间就把相应所有的属性,方法做一个总结。 UIBezierPath主要用来绘制矢量图形,它是基于Core Graphics对CGPathRef数据类型和path绘图属性的一个封装,所以是需要图形上下文的(CGContextRef),所以一般UIBezierPath在drawRect中使用。 UIBezierPath的属性介绍: 1.CGPath:将UIBezierPath类转换成CGPath,类似于UIColor的CGColor 2.empty:只读类型,路径上是否有有效的

iOS开发-图片上涂鸦绘制撤销功能

iOS开发-图片上涂鸦绘制撤销功能当我们需要重新在图片上进行绘制涂鸦生成新的图,这里使用到了Graphics中的API功能。Graphics Framework是一套基于C的API框架,使用了Quartz作为绘图引擎。它提供了低级别、轻量级、高保真度的2D渲染。微信搜索小游戏《全民保卫地球》玩玩吧,lets go。

一名开发者 947

通俗地解释一下 EMD(经验模态分解,Empirical Mode Decomposition)

EMD 就像把一碗“混在一起的面条”分成不同粗细的面条,方便你逐层分析每种波动。

qlkaicx的博客 1258

ios绘图demo,做一个涂鸦板(上)

ios绘图demo,做一个涂鸦板(上) 之前一篇文字写了ios绘图基础,这篇文章,使用之前写的绘图基础,做一个涂鸦板。并把每一步完成都结果都单独保存一个文件,加上v+版本号 ios绘图基础 ios绘图demo,做一个涂鸦板(上) 1完成一个最基本的涂鸦板2给涂鸦板加上颜色选择功能,和笔触粗细功能 ios绘图demo,做一个涂鸦板(下) 3画贝塞尔曲线

li_yangyang_li的博客 1215

MacOS上VScode配置PlatformIO Core的疑难杂症与提速实战

本文详细解析了在MacOS上使用VScode配置PlatformIO Core时遇到的安装卡死、新建项目缓慢等常见问题,并提供了官方脚本安装、网络优化、命令行预下载等实用解决方案。通过环境变量配置和镜像源加速,大幅提升开发效率,特别适合ESP32等嵌入式开发场景。

weixin_42567046的博客 228

Ubuntu系统下STM32开发环境搭建:从零配置CubeMX、VSCode与OpenOCD调试实战

本文详细介绍了在Ubuntu系统下搭建STM32开发环境的完整流程,包括CubeMX、VSCode和OpenOCD的安装配置。通过实战教程指导开发者从基础环境准备到工程创建与调试,提供高效的嵌入式开发解决方案,并分享常见问题解决方法。

potato的博客 948

ios-day17-03(使用UIBezierPath实现“涂鸦”小程序)

源码下载地址:http://download.csdn.net/detail/liu537192/8546721 效果图同ios-day17-02 核心代码除了JLPaintView.m,其他的都与ios-day17-02一样,下面附上JLPaintView.m的代码: // // JLPaintView.m // 02-涂鸦 // // Created b

liu537192的专栏 950

用ADSP-21569+SigmaStudio打造音频处理系统:从硬件连接到实时调参实战

本文详细介绍了如何利用ADSP-21569 DSP芯片和SigmaStudio图形化编程工具构建高性能音频处理系统。从硬件接口配置、信号流设计到实时参数调试,提供工业级开发中的实用技巧,包括低延迟优化、动态参数插值等关键技术,帮助开发者快速实现专业音频处理方案。

9o8p7i6u5y的博客 988

ios绘图demo,做一个涂鸦板(下)

ios绘图demo,做一个涂鸦板(下) 之前一篇ios绘图demo,做一个涂鸦板(上) 完成了一个基本功能的绘图板,这一篇,最要是增加一个画贝塞尔曲线的功能。 ios绘图基础 ios绘图demo,做一个涂鸦板(上) 1完成一个最基本的涂鸦板2给涂鸦板加上颜色选择功能,和笔触粗细功能 ios绘图demo,做一个涂鸦板(下) 3画贝塞尔曲线 | ios绘图

li_yangyang_li的博客 2215

换频道——假想《道德经》与量子力学的一些联系

之前看到一位AI PM的前辈分享了自己对于PM境界的看法: 境界一,行事被放心。 境界二,独立主导产品线从0到1,做正确的事,并把事做正确。 境界三,一切以灵魂境界为基础,产品作为其理念的衍生。 对于我,3个月尝试于目标而无获,但塞翁失马焉知非福。自己已经具备境界一,虽然境界二尚未成熟,但境界三却有幸有所思考。 今天,往澳门的动车途中有感而发,为随笔。

1026

DAMMFND: Domain-Aware Multimodal Multi-view Fake News Detection

虚假新闻的泛滥不仅严重阻碍了互联网社交媒体的健康发展,还在政治、经济和社会层面造成了实际危害,凸显了自动化虚假新闻检测的重要性(Zhou 等,2015;Cui 等,2019;Zhu 等,2022a;Li 等,2024c,b,a)。现有的虚假新闻检测方法通常聚焦于特定领域的新闻,例如健康或政治领域。然而,在现实世界中,社交媒体上的新闻往往跨越多个领域,这就要求现有的虚假新闻检测方法必须考虑多域泛化(Nan 等,2021;Qi 等,2019;Zhu 等,2022b)。

qq_52053775的博客 351

使用Bezier Paths[转]

使用UIBezierPath类可以创建基于矢量的路径。此类是Core Graphics框架关于path的一个封装。使用此类可以定义简单的形状,如椭圆或者矩形,或者有多个直线和曲线段组成的形状。1.Bezier Path 基础UIBezierPath对象是CGPathRef数据类型的封装。path如果是基于矢量形状的,都用直线和曲线段去创建。我们使用直线段去创建矩形和多边形,使用曲线段...

weixin_30867015的博客 320

QT里获取UUID当做唯一文件名称

QT里获取UUID当做唯一文件名称

559

Quartz2D之贝塞尔涂鸦板(UIBezierPath)

#import "DHPalette.h" @interface DHPalette () /**  记录所有路径的数组  */ @property (nonatomic, strong) NSMutableArray *paths; @end @implementation DHPalette

bjwltiankong的专栏 636

Python爬虫实战:利用Requests-HTML与异步技术高效爬取B站视频信息及弹幕数据分析

B站的弹幕,远非简单的评论功能,它是一种独特的、实时互动的社交方式,是观众情感的集体宣泄和共鸣。无论是用于内容创作者优化视频结构,还是用于社会学、传播学的研究,亦或是简单的个人兴趣分析,都具备极高的价值。stop_words = {'的', '了', '是', '我', '你', '他', '她', '它', '在', '有', '不', '吗', '吧', '啊', '这', '那'}本文不仅是代码的堆砌,更注重原理的剖析、反爬策略的应对以及工程化的思考,旨在为读者提供一份紧跟技术前沿的实战指南。

2201_76125261的博客 393

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

iOS 照片涂鸦功能的实现

作者 | 周强杏仁 APP 团队负责人,关注大前端。上个版本项目图片编辑需求中有一项涂鸦,涂鸦就是选取颜色后根据手指滑动路径在图片上生成对应路径,并最终生成一张新图片。接到项目,Google、Github 搜索一番,看到不少实现思路和 Demo,心想:so easy!然而,具体实现的时候却发现了这些 Demo 存在严重问题...初版实现实现了我们要的功能,是不是很完美?看效果是 OK,在讨论遇到的

杏仁技术站 2057

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

画板(CAShapeLayer实现)

// // DrawView.m // MyRefresh // // Created by tonniegao on 2016/12/16. // Copyright © 2016年 lagou. All rights reserved. // #import "DrawView.h" @interface DrawView() @property(nonatomic, stron

gaoyuqiang30的博客 878

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

使用UIBezierPath平滑的画线

UIBezierPath 是根据 Core Graphic Framework 写出的 Class ,能够让我们在 UIView 上画出我们需要的图形,主要就是一个UIBezierPath对象和一个UIColor对象保存画笔的颜色。 @implementation SmoothDrawDoodleView @synthesize parentView; @synthesize lastI

pingchangtan367的专栏 8889

iOS开发之涂鸦板

这是一个很简单的涂鸦板,只能在这里画线条而已~ 首先创建一个可变数组: #import "PaintView.h" //延展 在延展中声明的属性只能属于这个类 @interface PaintView () //用于保存所有线段的数组 @property(nonatomic, retain)NSMutableArray *allLines;

xfy6238的博客 822

在自己实现的ios画图程序中如何实现橡皮擦功能

通过cgcontextref来画图的时候,实现橡皮擦功能的方式有两种: 1. 将画笔设置为背景色来实现橡皮擦功能。 这种情况适用于当前设置context的blend mode为normal的时候,即 CGContextSetBlendMode(context, kCGBlendModeNormal); 此时设置背景色的代码如下: UIGraphicsBeginImageContext...

weixin_34075268的博客 510

iOS开发------iOS 10 由于权限问题导致崩溃的那些坑

6月份的WWDC大会结束有一段时间了,相信很多开发者也是在努力工作的闲时用着Xcode8 Beta版学习着新的特性吧。 使用Xcode写自己的东西有一段时间了,在使用Xcode8编程时不得不说我特别喜欢改后的默认字体,哈哈,当然默认字体是可以调回去的,只不过默认的字体感觉看起来比以前舒服了,毕竟不会像之前那么”字正腔圆”了。步入正题吧,不然慢慢的就会成为话唠了。凡事总会有个导火线吧,想记录权限问题的

RITL_Y 3万+
上一篇: iOS开发-------简易的人物信息浏览器(UISplitViewController分页控制器 与 UIWebView 网页界面)
下一篇: iOS开发-------UIAlertController(弹出视图控制器)
RITL
博客等级 码龄11年 69粉丝 77原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值