在superview objective-c中获取CGRect位置

时间:2013-06-12 10:14:52

标签: objective-c cocoa-touch

我想打印出CGRect的x坐标。 rect的x,y坐标设置为用户触摸的位置,如下所示:

- (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);
}

我可以打印出startPoint,但如果我打印出CGRect的坐标,我试着这样做:

int jrectX = lroundf(CGRectGetMinX(jrect));

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

但它返回的数字根本没有任何意义,有时它们在左边比在右边更大。代码有什么问题吗?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

DR.h

#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.
}

enter image description here