1

I want to print out the x coordinate of a CGRect. The x,y coordinates of the rect is set to where the user touches, like this:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    startPoint = [touch locationInView:self];
}

- (void)drawRect:(CGRect)rect
{
    ctx = UIGraphicsGetCurrentContext();
    jrect = CGRectMake(startPoint.x, startPoint.y, 100, 100);
    CGContextAddRect(ctx, jrect);
    CGContextFillPath(ctx);
}

I could just print out the startPoint but if I would print out the CGRect's coordinate I tried to do this:

int jrectX = lroundf(CGRectGetMinX(jrect));

xlabel.text = [NSString stringWithFormat:@"x: %i", jrectX];

But the number it returns doesn't make any sense at all, sometimes they are bigger to the left than to the right. Is there anything wrong with the code?

4

2 回答 2

2

CGRect 是一个具有四个 CGFloat 属性的结构:x、y、width、height

要从 CGRect 打印 x 值:

[NSString stringWithFormat:@"%f", rect.x]

要打印整个矩形,有一个方便的功能:

NSStringFromCGRect(rect)

您在上面遇到问题,因为您将 x 值存储到 int 中,然后在其上使用浮点舍入函数。所以应该是:

CGFloat jrectX = CGRectGetMinX(jrect);

. . . 除非您正在进行旋转变换,否则您可以使用:

CGFloat jrectX = jrect.origin.x;
于 2013-06-12T10:26:06.163 回答
0

博士

#import <UIKit/UIKit.h>

@interface DR : UIView
{
    CGContextRef ctx;
    CGRect jrect;
    CGPoint startPoint;

    UILabel *xlabel;
}

@end

DR.m 文件。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
         xlabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        [self addSubview:xlabel];
        // Initialization code
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    ctx = UIGraphicsGetCurrentContext();
    jrect = CGRectMake(startPoint.x, startPoint.y, 100, 100);

    CGContextAddRect(ctx, jrect);
    CGContextFillPath(ctx);
    // Drawing code
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    startPoint = [touch locationInView:self];

    int jrectX = lroundf(CGRectGetMinX(jrect));

    NSLog(@"jrectX --------------");
    xlabel.text = [NSString stringWithFormat:@"x: %i", jrectX];
    [self setNeedsDisplay];
}

@end

在其他 viewController 中使用它...

- (void)viewDidLoad
{
    DR *drr=[[DR alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [drr setBackgroundColor:[UIColor greenColor]];

    [self.view addSubview:drr];

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

在此处输入图像描述

于 2013-06-12T10:28:52.383 回答