如何在UIViewController中绘制

时间:2015-12-04 14:39:13

标签: ios objective-c uiview

我有这个绘制矩形的代码。

//// General Declarations
CGContextRef context = UIGraphicsGetCurrentContext();

//// Color Declarations
UIColor* color = [UIColor colorWithRed: 0.48 green: 0.833 blue: 0.38 alpha: 1];

//// Rectangle Drawing
CGRect rectangleRect = CGRectMake(58, 19, 85, 85);
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: rectangleRect];
[color setFill];
[rectanglePath fill];
{
    NSString* textContent = @"hello";
    NSMutableParagraphStyle* rectangleStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;
    rectangleStyle.alignment = NSTextAlignmentCenter;

    NSDictionary* rectangleFontAttributes = @{NSFontAttributeName: [UIFont fontWithName: @"HelveticaNeue" size: 42.5], NSForegroundColorAttributeName: UIColor.whiteColor, NSParagraphStyleAttributeName: rectangleStyle};

    CGFloat rectangleTextHeight = [textContent boundingRectWithSize: CGSizeMake(rectangleRect.size.width, INFINITY)  options: NSStringDrawingUsesLineFragmentOrigin attributes: rectangleFontAttributes context: nil].size.height;
    CGContextSaveGState(context);
    CGContextClipToRect(context, rectangleRect);
    [textContent drawInRect: CGRectMake(CGRectGetMinX(rectangleRect), CGRectGetMinY(rectangleRect) + (CGRectGetHeight(rectangleRect) - rectangleTextHeight) / 2, CGRectGetWidth(rectangleRect), rectangleTextHeight) withAttributes: rectangleFontAttributes];
    CGContextRestoreGState(context);
}

如果放在uiview子类中,代码可以正常工作,但是如何在不使用任何子类的情况下在主viewcontroller中使用它?有人可以转换代码,看看如何在viewcontroller中使用它?

我可以将UIBezierPath放在shapelayer中,但是带有文本的最后一部分我不知道该怎么做。请告诉我

1 个答案:

答案 0 :(得分:0)

你的问题没有任何意义。这就像问你如何让你的电脑烤蛋糕。

您需要阅读MVC设计模式。

视图控制器是控制器对象。它提供了控制一组视图的显示的逻辑,并在模型(数据)和构成屏幕内容的视图对象之间进行调解。

视图控制器不能也不应该绘制到屏幕上。他们拥有并管理绘制到屏幕的视图对象。

在封面下,视图对象使用图层渲染到屏幕。您可以向视图对象添加图层,也可以绘制这些图层。所以,是的,您可以在形状图层中放置一个贝塞尔曲线路径并将该图层添加到视图中,这将导致在绘制视图时绘制图层。