开发者

Moving multiple UIImageView with UIAccelerometer?

can anyone post or direct to how move multiple UIImag开发者_Go百科eView objects depending on the Accelerometer movement.

thanks.


The Apple guys provide this illustration of how to "smooth" the raw data coming from the accelerometer in the docs:

#define kFilteringFactor 0.1
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
  (UIAcceleration *)acceleration {
  // Use a basic low-pass filter to keep only the gravity component of each axis.
  accelX = (acceleration.x * kFilteringFactor) + (accelX * (1.0 - kFilteringFactor));
  accelY = (acceleration.y * kFilteringFactor) + (accelY * (1.0 - kFilteringFactor));
  accelZ = (acceleration.z * kFilteringFactor) + (accelZ * (1.0 - kFilteringFactor));
}

Once you have the data stream, simply alter the deltax,deltay you have for a set of images, within some minimum/maximum ranges, and reposition each UIImageView, eg:

// in your @interface somewhere
float deltax, deltay;
UIView* ivs[9];

// in your @implementation
#define MINXDELTA (-40)
#define MAXXDELTA (+40)
#define MINYDELTA (-40)
#define MAXYDELTA (+40)
#define SPEEDFACTOR (5)
#define kFilteringFactor 0.1
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
  (UIAcceleration *)acceleration {
  // Use a basic low-pass filter to keep only the gravity component of each axis.
  accelX = (acceleration.x * kFilteringFactor) + (accelX * (1.0 - kFilteringFactor));
  accelY = (acceleration.y * kFilteringFactor) + (accelY * (1.0 - kFilteringFactor));
  accelZ = (acceleration.z * kFilteringFactor) + (accelZ * (1.0 - kFilteringFactor));
  deltax+=accelX*SPEEDFACTOR; deltay+=accelY*SPEEDFACTOR;
  if (deltax<MINXDELTA) deltax=MINXDELTA;
  if (deltay<MINYDELTA) deltay=MINYDELTA;
  if (deltax>MINXDELTA) deltax=MINXDELTA;
  if (deltay>MINYDELTA) deltay=MINYDELTA;
  [self positionImages];
}
// call this from init too
-(void)positionImages {
  // assumes you have 9 images arranged as 3x3 on 40 pixel grid centered at 100,100
  for (ix=0; ix<3; ix++) for (iy=0; iy<3; iy++) {
    UIImageView *iv=ivs[ix+iy*3];
    CGPoint c=CGMakePoint(100-40+40*ix, 100-40+40*iy);
    iv.center=c;
  }
}

EDIT

Some minor typos above.

UIView* ivs[9];

should be

UIImageView* ivs[9];

and

  if (deltax>MINXDELTA) deltax=MINXDELTA;
  if (deltay>MINYDELTA) deltay=MINYDELTA;

should be

  if (deltax>MAXXDELTA) deltax=MAXXDELTA;
  if (deltay>MAXYDELTA) deltay=MAXYDELTA;

That's enough of a pointer / I'll leave it there I think.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜