質問

I am a new ios developer and here's my problem.I draw a shape with this code :

-(void)drawFirstShape:(float)xcoord :(float)ycoord :(CGContextRef)c {

float cote = 70.0f;
float x = 60.0f;
float y = 35.0f;
CGFloat strokecolor[4] = {1.0f, 1.0f, 1.0f, 1.0f};
CGContextSetStrokeColor(c, strokecolor);
CGContextSetLineWidth(c, 4.0f);
CGContextBeginPath(c);
CGContextMoveToPoint(c, xcoord, ycoord);
CGContextAddLineToPoint(c, xcoord+x, ycoord+y);
CGContextAddLineToPoint(c, xcoord+x, ycoord+cote+y);
CGContextAddLineToPoint(c, xcoord, ycoord+cote+2*y);
CGContextClosePath(c);
CGContextDrawPath(c, kCGPathStroke);
}

- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
[self drawFirstShape:160.0f :100.0f:c];
}

I want to create relative coordinates instead of absolute ones. The aim is to stabilize this code to use it with a 3.5inch and 4inch screen. Can someone help me please?

役に立ちましたか?

解決

If you want to use relative coordinates then use relative coordinates :) All positions and width/height should be defined as float or double from 0 to 1.
Then to get real coordinate - just multiply these relative coordinates to frame sizes (or to rect in your case) and you will get absolute coordinates or sizes.

Example (I just used your code with small changes. keep in mind that I changed sizes to relative and you will need to change them to be correct ones):

-(void)drawFirstShape:(float)xcoord :(float)ycoord :(CGContextRef)c inRect:(CGRect)rect{
    xcoord = xcoord*rect.size.width;
    ycoord = ycoord*rect.size.height;

    float cote = 0.07f*rect.size.width;
    float x = 0.05f*rect.size.width;
    float y = 0.025f*rect.size.height;
    CGFloat strokecolor[4] = {1.0f, 1.0f, 1.0f, 1.0f};
    CGContextSetStrokeColor(c, strokecolor);
    CGContextSetLineWidth(c, 4.0f);
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, xcoord, ycoord);
    CGContextAddLineToPoint(c, xcoord+x, ycoord+y);
    CGContextAddLineToPoint(c, xcoord+x, ycoord+cote+y);
    CGContextAddLineToPoint(c, xcoord, ycoord+cote+2*y);
    CGContextClosePath(c);
    CGContextDrawPath(c, kCGPathStroke);
}

- (void)drawRect:(CGRect)rect {
    CGContextRef c = UIGraphicsGetCurrentContext();
    [self drawFirstShape:0.2 :0.1 :c inRect:rect];
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top