绘制嵌套的UIView

时间:2013-05-25 15:11:24

标签: iphone ios ios6 uiview

我正在尝试按照本教程创建一个绘图应用程序:http://www.effectiveui.com/blog/2011/12/02/how-to-build-a-simple-painting-app-for-ios/,然后我尝试使其不仅仅在整个屏幕上绘制,我只绘制在内部的UIView另一个UIView。 (我称之为嵌套UIView)

我的代码目前在github:https://github.com/sammy0025/SimplePaint

我使用本教程中的原始代码调整的唯一部分是更改一些类前缀名称,启用ARC,因此没有deallocs,使用故事板(可以与教程中的原始代码一起使用),并更改此代码主视图控制器实现文件(SPViewController.m):

-(void)viewDidLoad
{
    [super viewDidLoad];
    nestedView.backgroundColor=[UIColor colorWithWhite:0 alpha:0]; //This is to make the nested view transparent
    SPView *paint = [[SPView alloc] initWithFrame:nestedView.bounds]; //original code is SPView *paint=[[SPView alloc] initWithFrame:self.view.bounds];
    [nestedView addSubview:paint]; //original code is [self.view addSubview:paint];
}

我的问题是如何确保我只在嵌套的UIView中绘制?

2 个答案:

答案 0 :(得分:0)

向子视图添加剪辑。例如。 self.bounds将涵盖视图的整个区域。

UIBezierPath *p = [UIBezierPath bezierPathWithRect:self.bounds];
[p addClip];

我认为视图的裁剪应该最初基于边界,并且可以通过添加新裁剪来缩小它。但这里的iOS和OS X之间可能存在差异。

答案 1 :(得分:0)

不要在嵌套视图中使用SPView,而应考虑更改SPView的框架以匹配您想要的内容。这应该可以解决您只允许在给定rect中绘图的问题。 我认为,由于您的故事板配置,您会看到问题。我不太了解故事板,但我能够通过抛出storyboard的视图并在viewDidAppear中构建自己的视图来以编程方式工作。

-(void)viewDidAppear:(BOOL)animated{

    UIView *newView = [[UIView alloc] initWithFrame:self.view.bounds];
    newView.backgroundColor = [UIColor greenColor];

    SPView *newPaint = [[SPView alloc] initWithFrame:CGRectInset(self.view.bounds, 40,40)];

    [newView addSubview:newPaint];

    self.view = newView;
}

screenshot of rebuilt view