我有一个自定义 UIView,我想在 drawRect: 方法中手动绘制。我希望视图是一个黑色矩形,有一个圆角,底部只有一个红色边框。如何实现 drawRect: 来绘制这个视图?
问问题
861 次
1 回答
1
我会做类似的事情
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
CGContextSaveGState(context);
CGFloat cornerRadius = 10.0f;
CGFloat redBorderHeight = 4.0f;
CGFloat minx = 0.0f;
CGFloat miny = 0.0f;
CGFloat midx = rect.size.width/2;
CGFloat midy = rect.size.height/2;
CGFloat maxx = rect.size.width;
CGFloat maxy = rect.size.height;
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, minx, midy);
CGPathAddArcToPoint(path, nil, minx, miny, midx, miny, 0);
CGPathAddArcToPoint(path, nil, maxx, miny, maxx, midy, 0);
CGPathAddArcToPoint(path, nil, maxx, maxy, midx, maxy, 0);
CGPathAddArcToPoint(path, nil, minx, maxy, minx, midy, cornerRadius);
CGPathCloseSubpath(path);
CGContextAddPath(context, path);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextDrawPath(context, kCGPathFill);
CGContextRestoreGState(context);
midy = (rect.size.height-redBorderHeight)/2;
maxy = rect.size.height-redBorderHeight;
CGMutablePathRef path2 = CGPathCreateMutable();
CGPathMoveToPoint(path2, nil, minx, midy);
CGPathAddArcToPoint(path2, nil, minx, miny, midx, miny, 0);
CGPathAddArcToPoint(path2, nil, maxx, miny, maxx, midy, 0);
CGPathAddArcToPoint(path2, nil, maxx, maxy, midx, maxy, 0);
CGPathAddArcToPoint(path2, nil, minx, maxy, minx, midy, cornerRadius);
CGPathCloseSubpath(path2);
CGContextAddPath(context, path2);
CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
CGContextDrawPath(context, kCGPathFill);
于 2013-05-01T05:30:56.273 回答