【发布时间】:2013-09-02 18:53:53
【问题描述】:
我在 viewController 上放置了一个视图,我想在这个视图中绘制一个矩形,但具有自定义高度。我根据 viewController 中的参数确定高度。 举个例子。如果我的参数是 50,我希望矩形的高度为 UIView 的 50%。
2 个问题:
如何将高度传递给自定义drawRect?
如何让矩形放置在 UIView 的底部?
我已经使用 Interface Builder 放置了视图,并在 UIView 的子类中实现了 drawRect,并将其用作 UIView 的自定义类。
所以在我的自定义类中:
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor * lightGrayColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:230.0/255.0 alpha:1.0];
CGRect paperRect = self.bounds;
drawLinearGradient(context, paperRect, lightGrayColor.CGColor, [UIColor clearColor].CGColor);
}
void drawLinearGradient(CGContextRef context, CGRect rect, CGColorRef startColor, CGColorRef endColor)
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };
NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGContextSaveGState(context);
CGContextAddRect(context, rect);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
这在我的视图中绘制了一个漂亮的渐变矩形,但它填充了整个 UIView。 这是因为 self.bounds。
我在自定义类中添加了一个属性 *height,但我不知道如何从我的 viewController 中填充它。所以我希望它从 UIView 的底部开始,并使其与我确定的一样高(实际高度的 %)。
有人知道我是怎么做到的吗?
【问题讨论】:
-
为什么不添加一个子视图(当前视图的 50%),然后填充它?