Рисование прямоугольников в iOS
Моя цель для моего приложения заключается в том, чтобы пользователь мог сортировать различные параметры планирования, прокручивая влево и вправо экрана iPhone. Как бы я рисовал и удалял прямоугольники, поскольку пользователь сортирует эти различные варианты планирования?
У меня есть файлы UIViewController.h, UIViewController.m и UIViewController.xib для управления. Нужен ли мне отдельный класс UIView? Если да, как мне связать этот класс UIView с представлением в моем файле .xib?
Ответы
Ответ 1
Вау... так много сложного решения, вот что вам нужно:
UIView *myBox = [[UIView alloc] initWithFrame:CGRectMake(180, 35, 10, 10)];
myBox.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:myBox];
Ничто другое... не нужно сходить с ума от реализации.
Ответ 2
// 1st Add QuartzCore.framework to your project "Link Binary with Libraries".
// 2nd Import the header in your .m file (of targeted view controller):
#import <QuartzCore/QuartzCore.h>
// 3rd Inside - (void)viewDidLoad method:
// Create a UIBezierPath (replace the coordinates with whatever you want):
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(10.0, 10.0)];
// # Entry Point with 10px white frame
[path moveToPoint:CGPointMake(10.0, 10.0)];
// # Keeping 10px frame with iPhone 450 on y-axis
[path addLineToPoint:CGPointMake(10.0, 450.0)];
// # Substracting 10px for frame on x-axis, and moving 450 in y-axis
[path addLineToPoint:CGPointMake(310.0, 450.0)];
// # Moving up to 1st step 10px line, 310px on the x-axis
[path addLineToPoint:CGPointMake(310.0, 10.0)];
// # Back to entry point
[path addLineToPoint:CGPointMake(10.0, 10.0)];
// 4th Create a CAShapeLayer that uses that UIBezierPath:
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [path CGPath];
shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
shapeLayer.lineWidth = 3.0;
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
Add that CAShapeLayer to your view layer:
// 5th add shapeLayer as sublayer inside layer view
[self.view.layer addSublayer:shapeLayer];
Ответ 3
Сначала создайте CustomView.
#import <UIKit/UIKit.h>
@interface MyView : UIView
@end
#import "MyView.h"
@implementation MyView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing Rect
[[UIColor redColor] setFill]; // red
UIRectFill(CGRectInset(self.bounds, 100, 100));
}
@end
вы проверяете. ссылка на ваш AppDelegate или ViewController
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
MyView* view = [[MyView alloc]initWithFrame:CGRectMake(10, 30, 300, 400)];
view.backgroundColor = [UIColor blackColor];
[window addSubview:view];
[self.window makeKeyAndVisible];
return YES;
}
- (void)viewDidLoad
{
MyView* view = [[MyView alloc]initWithFrame:CGRectMake(10, 30, 300, 400)];
view.backgroundColor = [UIColor blackColor];
[self.view addSubview:view];
[super viewDidLoad];
}
Ответ 4
A UIView
происходит в форме прямоугольника, поэтому, если вам нужно изменить цвет прямоугольника, установите для свойства backgroundColor
UIView цвет, которым вы хотите, чтобы он был.
Пустой UIView будет делать:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
view.backgroundColor = [UIColor redColor];
Если вы делаете это из конструктора интерфейса, перетащите новый вид из библиотеки на холст и установите цвет фона в свойствах представления.
Вам, вероятно, не нужен пользовательский вид для простого случая. Вы также можете добавить дополнительные элементы в ваш "прямоугольник", например, UILabels для отображения текста.
Ответ 5
Вы можете нарисовать прямоугольник, используя это:
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: CGRectMake(68, 38, 81, 40)];
[UIColor.grayColor setFill];
[rectanglePath fill];