public ParallaxImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Instantiate future objects mTranslationMatrix = new Matrix(); mSensorInterpreter = new SensorInterpreter(); // Sets scale type setScaleType(ScaleType.MATRIX); // Set available attributes if (attrs != null) { final TypedArray customAttrs = context.obtainStyledAttributes(attrs, R.styleable.ParallaxImageView); if (customAttrs != null) { if (customAttrs.hasValue(R.styleable.ParallaxImageView_intensity)) setParallaxIntensity( customAttrs.getFloat(R.styleable.ParallaxImageView_intensity, mParallaxIntensity)); if (customAttrs.hasValue(R.styleable.ParallaxImageView_scaledIntensity)) setScaledIntensities( customAttrs.getBoolean( R.styleable.ParallaxImageView_scaledIntensity, mScaledIntensities)); if (customAttrs.hasValue(R.styleable.ParallaxImageView_tiltSensitivity)) setTiltSensitivity( customAttrs.getFloat( R.styleable.ParallaxImageView_tiltSensitivity, mSensorInterpreter.getTiltSensitivity())); if (customAttrs.hasValue(R.styleable.ParallaxImageView_forwardTiltOffset)) setForwardTiltOffset( customAttrs.getFloat( R.styleable.ParallaxImageView_forwardTiltOffset, mSensorInterpreter.getForwardTiltOffset())); customAttrs.recycle(); } } // Configure matrix as early as possible by posting to MessageQueue post( new Runnable() { @Override public void run() { configureMatrix(); } }); }
/** * Sets the forward tilt offset dimension, allowing for the image to be centered while the phone * is "naturally" tilted forwards. * * @param forwardTiltOffset the new tilt forward adjustment */ public void setForwardTiltOffset(float forwardTiltOffset) { if (Math.abs(forwardTiltOffset) > 1) throw new IllegalArgumentException( "Parallax forward tilt offset must be less than or equal to 1.0"); mSensorInterpreter.setForwardTiltOffset(forwardTiltOffset); }
@Override public void onSensorChanged(SensorEvent event) { final float[] vectors = mSensorInterpreter.interpretSensorEvent(getContext(), event); // Return if interpretation of data failed if (vectors == null) return; // Set translation on ImageView matrix setTranslate(vectors[2], vectors[1]); }
/** * Sets the parallax tilt sensitivity for the image view. The stronger the sensitivity, the more a * given tilt will adjust the image and the smaller needed tilt to reach the image bounds. * * @param sensitivity the new tilt sensitivity */ public void setTiltSensitivity(float sensitivity) { mSensorInterpreter.setTiltSensitivity(sensitivity); }