[英]HOw to show a custom subclass of UIView in ViewController
Xcode 5
我正在尝试创建一个自定义裁剪矩形来裁剪图像。 我明白我需要在扩展UIView的类中覆盖drawRect()方法。 但后来我不知道如何在ViewController中使用该类来显示它。
如果我的方向错误,请更正。 我对此有点新意。
MDCustomCropRect.h
#import <UIKit/UIKit.h>
@interface MDCustomCropRect : UIView
@end
MDCustomCropRect.m
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGRect rectangle = CGRectMake(0, 100, 320, 100);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.0); //this is the transparent color
CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 0.5);
CGContextFillRect(context, rectangle);
CGContextStrokeRect(context, rectangle); //this will draw the border
}
只需将视图添加为UIViewController视图的子视图即可。
在viewController代码中,通常在viewDidLoad
方法中:
// create your view
MDCustomCropRect *myView = [[MDCustomCropRect alloc] init];
[self.view addSubView:myView]
// you can manually set your view frame - in this case use initWithFrame: instead of init
// OR use layout constraints : define and add constraints AFTER your inserted your view as a subview
编辑 :
在你的情况下,因为你只是绘制一个矩形 - 这是UIView
的 - 你可以改为:
UIView *myRectangleView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 320, 100)];
myRectangleView.backgroundColor = [UIColor clearColor];
myRectangleView.layer.borderWidth = 1;
myRectangleView.layer.borderColor = [UIColor colorWithWhite:0 alpha:0.5].CGColor;
[self.view addSubView:myRectangleView];
在您的情况下,不需要特定的drawRect
在你的viewController中
MDCustomCropRect *myView = [[MDCustomCropRect alloc] init];
myView.frame = CGRectMake(10,10,200,100);
myView.backgroundColor = [UIColor greenColor];
[self.view addSubView:myView]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.