Поворот двух UIImageViews на 360 градусов - PullRequest
1 голос
/ 23 ноября 2008

Я пытался сделать два UIImage вида фиксированного размера с изображениями на них (которые покрывают весь вид), но я очень старался (я сдаюсь!), Чтобы повернуть каждое из них по кругу , Так что если у меня есть один UIView, а другой прямо рядом с ним, я хотел бы иметь возможность повернуть первый (и другой сразу, без пробелов) после него, и вращаться на 360 градусов, это просто невозможно!

Может кто-нибудь помочь мне, пожалуйста?

1 Ответ

3 голосов
/ 01 декабря 2008

Одним из первых фрагментов кода iPhone, который я написал, было следующее, чтобы отобразить часы, сделанные из листьев.

Часы создаются из трех листьев, часов, минут и секунд, и у нас есть одно изображение листа, которое нарисовано с различным масштабированием, непрозрачностью и т. Д., Чтобы придать часам вид.

UIView ниже рисует часы в центре вида, используя перевод и масштабирование, чтобы расположить листья в нужном месте. CTM сохраняется и восстанавливается для сохранения повторных переводов.

Возможно, вы захотите посмотреть, поможет ли вам разобраться, как вы можете справиться с системами координат и вращением.

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) 
    {
        // Initialization code
        self.minutes = 49;
        self.seconds = 0;

        // clear to transparent
        self.clearsContextBeforeDrawing = YES;
        self.backgroundColor = [UIColor clearColor];

        [self tick:nil];
    }
    return self;
}

- (void)tick:(NSTimer *)timer
{
    // get time
    NSDate * time = [NSDate date];
    NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents * comp = [gregorian components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:time];

    // update the time
    self.seconds = [comp second];
    self.minutes = [comp minute];
    self.hours = [comp hour];

    // redisplay
    [self setNeedsDisplay];
}

- (float)toRadians:(float)deg
{
    return deg * 3.14/180.0;
}

- (void)drawClock:(CGPoint)pos hours:(NSInteger)theHours minutes:(NSInteger)theMinutes seconds:(NSInteger)theSeconds
{
    UIImage * leaf = [UIImage imageNamed:@"leaf.png"];

    // context
    CGContextRef myContext = UIGraphicsGetCurrentContext();

    // save original state
    CGContextSaveGState(myContext);

    // set alpha and move it to centre of clock
    CGContextSetAlpha(myContext, 0.8);
    CGContextTranslateCTM (myContext, pos.x, pos.y);

    // save centred state
    CGContextSaveGState(myContext);

    // rotate and translate the hour 'hand'
    CGContextRotateCTM (myContext, [self toRadians:(theHours-3.0+theMinutes/60.0)*360/12.0 - 10] );
    CGContextTranslateCTM (myContext, -5, -[leaf size].height/12);

    // draw the hour hand and restore to translated
    CGContextDrawImage(myContext, CGRectMake(0, 0, [leaf size].width/6, [leaf size].height/6), [leaf CGImage]);

    // restore centred state and resave
    CGContextRestoreGState(myContext);
    CGContextSaveGState(myContext);

    // rotate and transform the minute 'hand'
    CGContextRotateCTM (myContext, [self toRadians:((theMinutes-15)*360.0 /60.0) - 10]);
    CGContextTranslateCTM (myContext, -5, -[leaf size].height/10);

    // draw the minute hand and restore original context
    CGContextDrawImage(myContext, CGRectMake(0, 0, [leaf size].width/5, [leaf size].height/5), [leaf CGImage]);

    // restore centred state
    CGContextRestoreGState(myContext);

    // rotate and transform the second 'hand'
    CGContextSetAlpha(myContext, 0.5);
    CGContextRotateCTM (myContext, [self toRadians:((theSeconds-15)*360 /60.0) - 10]);
    CGContextTranslateCTM (myContext, -5, -[leaf size].height/10);

    // draw the second hand and restore original context
    CGContextDrawImage(myContext, CGRectMake(0, 0, [leaf size].width/5, [leaf size].height/5), [leaf CGImage]);
    CGContextRestoreGState(myContext);
}

- (void)drawRect:(CGRect)rect
{
    // draw clock in clock view
    [self drawClock:CGPointMake(rect.size.width/2,rect.size.height/2) hours:self.hours minutes:self.minutes seconds:self.seconds];

    // test code for centering hands
//  [self drawClock:CGPointMake(rect.size.width/2,rect.size.height/2) hours:12 minutes:00 seconds:00];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...