我有一个uiview子类,我试图用投影绘制圆角矩形。虽然它绘制了两个元素,但我可以通过圆角矩形填充看到阴影。我是CG的新手,所以我可能会错过简单的东西(尽管它似乎不是填充的alpha值设置为1)。这是绘制矩形代码。带圆角矩形和阴影的UIView:阴影出现在矩形上方
- (void)drawRect:(CGRect)rect {
// get the contect
CGContextRef context = UIGraphicsGetCurrentContext();
//for the shadow, save the state then draw the shadow
CGContextSaveGState(context);
CGContextSetShadow(context, CGSizeMake(4,-5), 10);
//now draw the rounded rectangle
CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
//since I need room in my rect for the shadow, make the rounded rectangle a little smaller than frame
CGRect rrect = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect), CGRectGetWidth(rect)-30, CGRectGetHeight(rect)-30);
CGFloat radius = self.cornerRadius;
// the rest is pretty much copied from Apples example
CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect);
CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect);
// Start at 1
CGContextMoveToPoint(context, minx, midy);
// Add an arc through 2 to 3
CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
// Add an arc through 4 to 5
CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
// Add an arc through 6 to 7
CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
// Add an arc through 8 to 9
CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
// Close the path
CGContextClosePath(context);
// Fill & stroke the path
CGContextDrawPath(context, kCGPathFillStroke);
//for the shadow
CGContextRestoreGState(context);
}
阅读这篇博客http://bynomial.com/blog/?p=52&cpage=1#comment-1115。它回答了如何做到这一点。 – 2011-09-27 17:09:03
这里记录的解决方案对我来说是最好的,因为它向我展示了如何使用自定义图像(带有maskToBounds = YES)以及阴影。谢谢! – Mark 2011-11-12 20:04:44
@John:很多人都很感谢这个链接,哥们......帮助我开始。 :) – viral 2012-02-22 06:36:01