自动调整UIView的圆角

时间:2012-05-28 15:21:41

标签: ios uiview autosize

是否可以将圆角( topLeft和topRight )设置为自动调整uiview? 这是我的代码:

SFDetailViewController.h

@interface SFDetailViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, PopoverViewListDelegate>
{
  ...

  UIView *header;
}
@property (nonatomic, retain) IBOutlet UIView *header;

@end

SFDetailViewController.m

#import "SFDetailViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface SFDetailViewController ()
@end


@implementation SFDetailViewController
@syntesyze header;

-(void) viewDidLoad
{
    ....
    [self setCornerRadiusToHeader:header];
 }



-(void) setCornerRadiusToHeader:(UIView *)headerView
{    
    CGRect bounds = headerView.layer.bounds;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds 
                                               byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
                                                     cornerRadii:CGSizeMake(8.0, 8.0)];

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = bounds;
    maskLayer.path = maskPath.CGPath;

    [headerView.layer addSublayer:maskLayer];
    headerView.layer.mask = maskLayer; 

}

视图在IB中定义为:

IB

我得到的 - topRight角是直的,因为视图的大小是动态的。

result

2 个答案:

答案 0 :(得分:2)

您需要将UIView的{​​{1}}属性设置为contentMode。内容模式控制视图内容在其边界更改时的更改方式(如自动化时)。默认情况下,它只是拉伸视图的内容,这就是角落伸展的原因。

答案 1 :(得分:1)

解决方案:

感谢jbrennan,我设置了

header.contentMode = UIViewContentModeRedraw;

然后,在viewDidLoad中我打电话:

[header setNeedsDisplay];

顺便说一下,我写了(void)drawRect:(CGRect)rect,我写了以下内容:

- (void)drawRect:(CGRect)rect
{ 
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect); 

    UIColor *color = [UIColor lightGrayColor];
    CGContextSetFillColorWithColor(context, color.CGColor);

    CGRect rrect = CGRectMake(CGRectGetMinX(rect)-2, CGRectGetMinY(rect), CGRectGetWidth(rect)+4, CGRectGetHeight(rect) + 1);
    CGFloat radius = 10.0f;

    CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect);
    CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect);

    CGContextMoveToPoint(context, minx, midy);
    CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
    CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
    CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, 0);
    CGContextAddArcToPoint(context, minx, maxy, minx, midy, 0);
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFill);

}

结果:

result