Отображение UIBezierPath на представлении - PullRequest
8 голосов
/ 28 июля 2010

В одном из моих методов у меня есть этот код:

-(void)myMethod {   
   UIBezierPath *circle = [UIBezierPath
                       bezierPathWithOvalInRect:CGRectMake(75, 100, 200, 200)];  
}

Как мне заставить его показываться на виде?

Я попробовал addSubview, но он дал мне incompatible type error, потому что ожидал UIView.

Я уверен, что это должно быть просто.

Спасибо

Ответы [ 5 ]

27 голосов
/ 08 мая 2012

Просто подумал, что добавлю, что вам не обязательно рисовать это в методе drawRect: UIView. Вы можете нарисовать его где угодно, если вы это делаете внутри контекста изображения UIGraphics. Я делаю это все время, когда не хочу создавать подкласс UIView. Вот рабочий пример:

UIBezierPath *circle = [UIBezierPath
                        bezierPathWithOvalInRect:CGRectMake(75, 100, 200, 200)];  

//you have to account for the x and y values of your UIBezierPath rect
//add the x to the width (75 + 200)
//add the y to the height (100 + 200)
UIGraphicsBeginImageContext(CGSizeMake(275, 300));

//this gets the graphic context
CGContextRef context = UIGraphicsGetCurrentContext();

//you can stroke and/or fill
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);
[circle fill];
[circle stroke];

//now get the image from the context
UIImage *bezierImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageView *bezierImageView = [[UIImageView alloc]initWithImage:bezierImage];

Теперь просто добавьте UIImageView в качестве подпредставления.

Кроме того, вы можете использовать это и для другого рисунка. Опять же, после небольшой настройки, он работает так же, как drawRect: метод.

//this is an arbitrary size for example
CGSize aSize = CGSizeMake(50.f, 50.f);

//this can take any CGSize
//it works like the frame.size would in the drawRect: method
//in the way that it represents the context's size
UIGraphicsBeginImageContext(aSize);

//this gets the graphic context
CGContextRef context = UIGraphicsGetCurrentContext();

//you can do drawing just like you would in the drawRect: method
//I am drawing a square just for an example to show you that you can do any sort of drawing in here
CGContextMoveToPoint(context, 0.f, 0.f);
CGContextAddLineToPoint(context, aSize.width, 0.f);
CGContextAddLineToPoint(context, aSize.width, aSize.height);
CGContextAddLineToPoint(context, 0.f, aSize.height);
CGContextClosePath(context);

//you can stroke and/or fill
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);
CGContextDrawPath(context, kCGPathFillStroke);

//now get the image from the context
UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageView *squareImageView = [[UIImageView alloc]initWithImage:squareImage];

Редактировать: Одна вещь, которую я должен добавить, заключается в том, что для любого современного рисунка такого рода, вы должны поменяться

UIGraphicsBeginImageContext(size);

для

UIGraphicsBeginImageContextWithOptions(size, opaque, scale);

Это правильно нарисует вашу графику для дисплеев сетчатки и не сетчатки.

К вашему сведению, UIGraphicsBeginImageContext(size) эквивалентно UIGraphicsBeginImageContextWithOptions(size, FALSE, 1.f), что вполне подходит для дисплеев без сетчатки, которые могут иметь некоторую прозрачность.

Однако, если вам не нужна прозрачность, она более оптимизирована для передачи значения TRUE для непрозрачного аргумента.

Самый безопасный и рекомендуемый способ рисования - передать [[UIScreen mainScreen]scale] в качестве аргумента масштаба.

Так что для приведенного выше примера (ов) вы должны использовать это вместо:

UIGraphicsBeginImageContextWithOptions(aSize, FALSE, [[UIScreen mainScreen] scale]);

Для получения дополнительной информации, проверьте Документы Apple .

18 голосов
/ 28 июля 2010

Вы можете нарисовать его, используя методы fill или stroke, например, в реализации drawInRect: пользовательского представления:

- (void)drawRect:(CGRect)rect {
    // Drawing code
    UIBezierPath *circle = [UIBezierPath
                    bezierPathWithOvalInRect:CGRectMake(75, 100, 200, 200)];  
    [circle fill];
}
10 голосов
/ 31 мая 2014

Вы также можете добавить UIBezierPath в UIView без создания подклассов с помощью CAShapeLayer.

Например, чтобы добавить свой путь в виде белой линии 3pt с центром в UIView:

UIBezierPath *mybezierpath = [UIBezierPath
                    bezierPathWithOvalInRect:CGRectMake(0, 0, 100, 100)];  

CAShapeLayer *lines = [CAShapeLayer layer];
lines.path = mybezierpath.CGPath;
lines.bounds = CGPathGetBoundingBox(lines.path);
lines.strokeColor = [UIColor whiteColor].CGColor;
lines.fillColor = [UIColor clearColor].CGColor; /*if you just want lines*/
lines.lineWidth = 3;
lines.position = CGPointMake(self.myview.frame.size.width/2.0, self.myview.frame.size.height/2.0);
lines.anchorPoint = CGPointMake(.5, .5);

[self.myview.layer addSublayer:lines];
2 голосов
/ 28 июля 2010

Рисование является эксклюзивным представлением видов. Создайте пользовательское представление, укажите его путь и реализуйте метод представления drawRect: для заполнения и / или обводки пути.

1 голос
/ 02 августа 2016

В Swift 2.0:

let path = UIBezierPath()

let p1 = CGPointMake(0,self.view.frame.height/2)
let p3 = CGPointMake(self.view.frame.width,self.view.frame.height/2)

path.moveToPoint(p1)
path.addQuadCurveToPoint(p3, controlPoint: CGPoint(x: self.view.frame.width/2, y: 0))

let line = CAShapeLayer()
line.path = path.CGPath;
line.strokeColor = UIColor.blackColor().CGColor
line.fillColor = UIColor.redColor().CGColor
view.layer.addSublayer(line)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...