iOS*_*iOS 1 iphone objective-c ios objective-c-category uibezierpath
我试图在UIView类别中使用UIBezierPath创建一个三角形.但没有显示三角形.还得到一个:CGContextSetFillColorWithColor.所以我的问题是如何使用UIView类别制作三角形或任何路径.演示项目
#import "UIView+Bubble.h"
#import <QuartzCore/QuartzCore.h>
@implementation UIView (Bubble)
+(UIView *)makeBubble{
UIView *customView = [[UIView alloc] init];
customView.frame=CGRectMake(0, 0, 320, 500);
UIBezierPath *triangle = [UIBezierPath bezierPath];
[triangle moveToPoint:CGPointMake(100, 0)];
[triangle addLineToPoint:CGPointMake(0, 100)];
[triangle addLineToPoint:CGPointMake(200, 100)];
[triangle closePath];
[[UIColor blackColor] setFill];
[triangle fill];
customView.layer.shadowPath = [triangle CGPath];
return customView;
}
@end
Run Code Online (Sandbox Code Playgroud)
在ViewController.m中使用它像: -
- (void)viewDidLoad
{
UIView *helpBubble=[UIView makeBubble];
[self.view addSubview:helpBubble];
}
Run Code Online (Sandbox Code Playgroud)
在UIView + Bubble.h类别中,UIBezierPath尝试在空上下文中绘制三角形.如果您想使用上面的UIBezierPath绘制形状,则必须将此代码放在drawRectView类的方法中.
另一方面,您可以创建一个新的上下文来绘制.您可以修改makeBubble方法,如下所示:
+(UIView *)makeBubble{
// declare UIimageView, not UIView
UIImageView *customView = [[UIImageView alloc] init];
customView.frame=CGRectMake(0, 0, 320, 500);
// create a new contex to draw
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), NO, 0);
UIBezierPath *triangle = [UIBezierPath bezierPath];
[triangle moveToPoint:CGPointMake(100, 0)];
[triangle addLineToPoint:CGPointMake(0, 100)];
[triangle addLineToPoint:CGPointMake(200, 100)];
[triangle closePath];
[[UIColor blackColor] setFill];
[triangle fill];
customView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return customView;
}
Run Code Online (Sandbox Code Playgroud)
为了使它动态,你可以传递一个cgRect参数,比如
+(UIView *)makeBubble:(CGRect)rect
Run Code Online (Sandbox Code Playgroud)
也更改为customView.frame=rect;与UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);该方法内.并调用makeBubble:(CGRect)rect方法作为
UIView *helpBubble=[UIView makeBubble:/*your desire rect*/];
Run Code Online (Sandbox Code Playgroud)
如果根据矩形计算得分,那将是很好的.
| 归档时间: |
|
| 查看次数: |
1785 次 |
| 最近记录: |