iOS绘制带有底部边框的自定义视图

时间:2013-05-01 04:38:48

标签: ios uiview drawrect

我有一个自定义的UIView,我想在drawRect:方法中手动绘制。我希望视图是一个黑色矩形,只有一个圆角和一个红色边框。如何实现drawRect:绘制此视图?

Sample UIView

1 个答案:

答案 0 :(得分: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);