当前位置: 代码迷 >> Iphone >> drawRect中怎么自定义UIView形状?小弟我的代码有些有关问题
  详细解决方案

drawRect中怎么自定义UIView形状?小弟我的代码有些有关问题

热度:61   发布时间:2016-04-25 05:54:04.0
drawRect中如何自定义UIView形状??我的代码有些问题
我有一个类继承自  UIView,我想在drawRect中将view画成多边形。我已经画出了形状(红色部分),但我想把蓝色部分给裁剪掉,但我用了CGContexClip竟没有效果,请问我代码里哪里出问题啦???



 

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor blueColor]];
    }
    return self;
}
- (void)drawRect:(CGRect)rect //画出边框
{
   CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGFloat arrowHeight = 15.0;
    CGFloat arrowWidth = 13.0;
    CGPoint arrowPoint = CGPointMake(rect.origin.x+rect.size.width/2.0f,rect.origin.y);
    CGMutablePathRef arrowPath = CGPathCreateMutable();
    CGPathMoveToPoint(arrowPath, NULL, arrowPoint.x, arrowPoint.y);
    CGPathAddLineToPoint(arrowPath, NULL, arrowPoint.x, arrowPoint.y+arrowHeight);
    CGPathAddLineToPoint(arrowPath, NULL, rect.origin.x, rect.origin.y+arrowHeight);
    CGPathAddLineToPoint(arrowPath, NULL, rect.origin.x, rect.origin.y+rect.size.height);
    CGPathAddLineToPoint(arrowPath, NULL, rect.origin.x+rect.size.width, rect.origin.y+rect.size.height);
    
    CGPathAddLineToPoint(arrowPath, NULL, rect.origin.x+rect.size.width, rect.origin.y+arrowHeight);
    CGPathAddLineToPoint(arrowPath, NULL, arrowPoint.x+arrowWidth, rect.origin.y+arrowHeight);
    CGPathCloseSubpath(arrowPath); //封口
    CGContextAddPath(ctx, arrowPath);
   
    [[UIColor redColor] setFill];
    CGContextDrawPath(ctx,kCGPathFill);
    CGContextClip(ctx);
    CGPathRelease(arrowPath);
}
多谢多谢!!
drawRect 自定义UIView

------解决方案--------------------
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor blueColor]];//此句修改成 [self setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}
------解决方案--------------------
设置成背景透明,画之前先调用清除cgcontext中的内容。