簡體   English   中英

自動調整UIView的圓角

[英]Round corners for autosizing UIView

是否可以使圓角( 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角是直的,因為視圖的大小是動態的。

結果

您需要將UIViewcontentMode屬性設置為類似UIViewContentModeRedrew屬性。 內容模式控制視圖內容在其邊界更改時的更改方式(如自動化時)。 默認情況下,它只會拉伸視圖的內容,這就是角落伸展的原因。

解:

感謝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);

}

結果:

結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM