【问题标题】:core graphics drawRect specify coordinates核心图形 drawRect 指定坐标
【发布时间】:2011-10-21 06:38:43
【问题描述】:

我刚刚进入 iOS 开发。我正在修改核心图形,并且试图弄清楚如何限制绘图的大小,并将其放置在屏幕上的特定坐标处。这是我的 HomeViewController.m loadView AND addCircle 方法,以及我的 Artist.m drawRect 方法:

HomeViewController.m -> 加载视图

- (void)loadView
{
    NSLog(@"HomeViewController.m : loadView");
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UILabel *lbl;
    lbl = [[UILabel alloc] initWithFrame:CGRectMake(65, 50, 220, 70)];
    lbl.text = @"Home Screen";
    lbl.font = [UIFont boldSystemFontOfSize:30];
    [self.view addSubview:lbl];
    [lbl release];

    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoDark ];
    infoButton.frame = CGRectMake(10, 10, 300, 300);
    [self.view addSubview:infoButton];
    [infoButton addTarget:self action:@selector(loadInfo) forControlEvents:UIControlEventTouchUpInside];
    [infoButton release];

    [self addCircle];

    // self.view = [[[Artist alloc] init] autorelease];
}

HomeViewController.m -> addCircle

- (void)addCircle
{
    Artist *artist = [[[Artist alloc] init] autorelease];
    [self.view addSubview:artist];
    // [artist drawRect:CGRectMake(100, 100, 100, 100)];
}

Artist.m -> drawRect

- (void)drawRect:(CGRect)rect
{
    NSLog(@"Artist.m : drawRect");
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGColorRef red = [[UIColor redColor] CGColor];

    CGContextFillRect(context, CGRectMake(130,200,120,120));
    CGContextSetFillColorWithColor(context,red);
    CGContextFillEllipseInRect(context, CGRectMake(130, 200, 120, 120));
}

基本上,我试图避免让绘图占据整个屏幕,而是将其限制在我制作的大小并位于其他视图之上。

【问题讨论】:

  • NSLog(@"%s", __func__); 将记录当前函数的名称或当前方法的签名。
  • 真棒花絮,谢谢!我一直试图弄清楚如何将信息转储到 NSLog 而非文本字符串。
  • 另外,您可能希望释放您分配给self.view 的视图。您通过view 属性拥有它,并且您还拥有它,因为您创建了它,因此它被拥有两次。如果您从不释放该创建所有权,您将泄漏它。相反,因为您没有使用alloc 创建 UIButton,所以您拥有它并且不应该释放它。有关详细信息,请参阅内存管理编程指南:developer.apple.com/library/ios/documentation/Cocoa/Conceptual/…

标签: iphone ios cocoa-touch core-graphics


【解决方案1】:

在您的UIViewControllerviewDidLoad 方法中调用[self.view addSubview:artistView] 将您的自定义视图添加到现有视图中。然后使用frame 属性设置它的大小和位置。

【讨论】:

  • 不幸的是,我在发布之前尝试过。 Artist 的 init 方法可以正常触发,但 drawRect 没有被调用。
  • 你没有设置艺术家视图的框架。
  • 是的,我注意到大约在您发表评论的同时。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多