Форум программистов, компьютерный форум, киберфорум
Программирование Android
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
1 / 1 / 0
Регистрация: 13.01.2013
Сообщений: 130
1

Параллакс в живых обоях

20.10.2013, 01:22. Показов 831. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
есть ли у кого исходник работающего простейшего кода параллакс-эффектом?
или помогите в моем, не знаю почему, не работающем примере:
Кликните здесь для просмотра всего текста

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package live.wallpaper.parall;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.view.SurfaceHolder;
 
public class DemoWallpaperService extends WallpaperService {
     
    @Override
    public Engine onCreateEngine() {
           return new DemoWallpaperEngine();
    }
    
    private class DemoWallpaperEngine extends Engine {
        Bitmap pic = BitmapFactory.decodeResource(getResources(), R.drawable.gear);
        Bitmap bg = BitmapFactory.decodeResource(getResources(), R.drawable.bg7);
        
        private boolean mVisible = false;
        private final Handler mHandler = new Handler();
        private final Runnable mUpdateDisplay = new Runnable() {
            public void run() {
                draw();
            }
        };
        int offsetX;
        @Override
        public void onOffsetsChanged(float xOffset, float yOffset,
                float xOffsetStep, float yOffsetStep, int xPixelOffset,
                int yPixelOffset) {
            
            this.offsetX = xPixelOffset;
        
            super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep,
                    xPixelOffset, yPixelOffset);
        }
        @Override
        public void onVisibilityChanged(boolean visible) {
            mVisible = visible;
            if (visible) {
                draw();
            } else {
                mHandler.removeCallbacks(mUpdateDisplay);
            }
        }
 
        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format,
                int width, int height) {
            draw();
        }
 
        @Override
        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
            mVisible = false;
            mHandler.removeCallbacks(mUpdateDisplay);
        }
 
        @Override
        public void onDestroy() {
            super.onDestroy();
            mVisible = false;
            mHandler.removeCallbacks(mUpdateDisplay);
        }
 
        int rotation = 1;
        int bmpWidth = pic.getWidth();
        
        
        private void draw() {
            SurfaceHolder holder = getSurfaceHolder();
            setTouchEventsEnabled(true);
            Canvas c = null;
            try {
                c = holder.lockCanvas();
               
                if (c != null) {
                    Paint p = new Paint();
                    p.setAntiAlias(false);
                    rotation += 8;
                    if (rotation > 360) {rotation = 1;}
                    c.drawBitmap(bg, this.offsetX, 0, p);                                                                                                        
                    
c.rotate(rotation, 170+bmpWidth/2+this.offsetX, 100+bmpWidth/2);
c.drawBitmap(pic, 170+this.offsetX, 100, p);
c.rotate(-rotation);
                 }
            } finally {
                if (c != null)
                    holder.unlockCanvasAndPost(c);
            }
            mHandler.removeCallbacks(mUpdateDisplay);
            if (mVisible) {
                mHandler.postDelayed(mUpdateDisplay, 20);
            }
 
        }
        
            
        
    }
}
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package live.wallpaper.parall;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.os.Handler;
import android.view.Display;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.animation.Interpolator;
import android.widget.Scroller;
 
public class ZTouchMove {
    
    public interface ZTouchMoveListener {
        public void onTouchOffsetChanged(float xOffset);
    }
    private List<ZTouchMoveListener> mListeners = new ArrayList<ZTouchMoveListener>();
    
    public class ZInterpolator implements Interpolator {
        public float getInterpolation(float input) {
            // f(x) = ax^3 + bx^2 + cx + d
            // a = x - 2
            // b = 3 - 2x
            // c = x
            // d = 0
            // where x = derivative in point 0
            //input = (float)(-Math.cos(10*((double)input/Math.PI)) + 1) / 2;
            input = (mVelocity - 2) * (float) Math.pow(input, 3) + (3 - 2 * mVelocity) * (float) Math.pow(input, 2) + mVelocity * input; 
            return input;
        }
    }
    
    Handler mHandler = new Handler();
    
    final Runnable mRunnable = new Runnable()
    {
        public void run() 
        {
            if(onMovingToPosition())
                mHandler.postDelayed(this, 20);
        }
    };
    
    private float mPosition = 0.5f;
    private float mPositionDelta = 0;
    private float mTouchDownX;
    private int xDiff;
    private VelocityTracker mVelocityTracker;
    private float mVelocity = 0;
    private Scroller mScroller;
    
    private final static int TOUCH_STATE_REST = 0;
    private final static int TOUCH_STATE_SCROLLING = 1;
    private static final int SCROLLING_TIME = 300;
    private static final int SNAP_VELOCITY = 350;
    
    private int mTouchSlop;
    private int mMaximumVelocity;   
    private int mTouchState = TOUCH_STATE_REST;
    
    private int mWidth;
    private int mNumVirtualScreens = 5;
    
    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public void init(Context ctx) {
        mScroller = new Scroller(ctx, new ZInterpolator());
        
        final ViewConfiguration configuration = ViewConfiguration.get(ctx);
        mTouchSlop = configuration.getScaledTouchSlop();
        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
 
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
 
        // API Level 13
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            Point size = new Point();
            display.getSize(size); 
            mWidth = size.x;            
        } else {
            // API Level <13
            mWidth = display.getWidth();            
        }
    }
    
    public void onTouchEvent(MotionEvent e) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(e);
        
        final float x = e.getX();
        final int action = e.getAction();
        
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                
                mTouchDownX = x;
                break;
                
            case MotionEvent.ACTION_MOVE:
                xDiff = (int) (x - mTouchDownX);
                
                if (Math.abs(xDiff) > mTouchSlop && mTouchState != TOUCH_STATE_SCROLLING) {
                    mTouchState = TOUCH_STATE_SCROLLING;
                    if(xDiff < 0)
                        mTouchDownX = mTouchDownX - mTouchSlop;
                    else
                        mTouchDownX = mTouchDownX + mTouchSlop;
                    xDiff = (int) (x - mTouchDownX);
                }
                
                if (mTouchState == TOUCH_STATE_SCROLLING) {
                    mPositionDelta = -(float)xDiff / (mWidth * mNumVirtualScreens);
                    
                }
                break;
                
            case MotionEvent.ACTION_UP:
                if (mTouchState == TOUCH_STATE_SCROLLING) {
                    final VelocityTracker velocityTracker = mVelocityTracker;
                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
                    float velocityX = velocityTracker.getXVelocity() / (float)(mNumVirtualScreens * mWidth);
                    
                    mPosition =  mPosition + mPositionDelta;
                    mPositionDelta = 0;
                    
                    if(!returnSpring()) {
                        mVelocity = Math.min(3, Math.abs(velocityX * mNumVirtualScreens)) ;
                        // deaccelerate();
                        // Inertion
                        if(Math.abs(velocityX) * (float)(mNumVirtualScreens * mWidth) > SNAP_VELOCITY)
                            moveToPosition(mPosition, mPosition - (velocityX > 0 ? 1 : -1) * 1 / (float) mNumVirtualScreens );
                        else
                            moveToPosition(mPosition, mPosition - 0.7f * velocityX * ((float)SCROLLING_TIME / 1000) );                      
                    }                   
                }               
                mTouchState = TOUCH_STATE_REST;
                break;
                
            case MotionEvent.ACTION_CANCEL:
                mTouchState = TOUCH_STATE_REST;
                mPositionDelta = 0;
                break;
        }
        dispatchMoving();
    }
    
    private boolean returnSpring() {
        mVelocity = 0;
        if(mPositionDelta + mPosition > 1 - 0.5 / (float) mNumVirtualScreens)
            moveToPosition(mPosition, (float) (1 - 0.5 / (float) mNumVirtualScreens));
        else if(mPositionDelta + mPosition < 0.5 / (float) mNumVirtualScreens)
            moveToPosition(mPosition, (float) 0.5 / (float) mNumVirtualScreens);
        else
            return false;
        return true;
    }
    
    private void moveToPosition(float current_position, float desired_position) {
        mScroller.startScroll((int)(current_position * 1000), 0, (int)((desired_position - current_position) * 1000), 0, SCROLLING_TIME);
        mHandler.postDelayed(mRunnable, 20);
    }
    
    private boolean onMovingToPosition() {
        if(mScroller.computeScrollOffset()) {
            mPosition = (float)mScroller.getCurrX() / 1000;
            dispatchMoving();
            return true;
        } else {
            returnSpring();
            return false;
        }
    }
    
    private float normalizePosition(float xOffset) {
        final float springZone = 1 / (float) mNumVirtualScreens;
        // Normalized offset is from 0 to 0.5
        float xOffsetNormalized = Math.abs(xOffset - 0.5f);
        if(xOffsetNormalized + springZone / 2 > 0.5f) {
            // Spring formula
            // (0.5 - 2 * (1 - (x / (2 * springZone) + 0.5))^2) * springZone
            // where x >=0 and <= springZone
            // delta y = springZone / 2, y >=0 and y <= springZone / 2
            xOffsetNormalized = 0.5f - springZone / 2 + 
                    (0.5f - 2 * (float)Math.pow( (double)(1 - ( (xOffsetNormalized - 0.5f + springZone / 2) / (2 * springZone) + 0.5)), 2 ) ) * springZone;
            
            if(xOffset < 0.5f)
                xOffset = 0.5f - xOffsetNormalized;  
            else
                xOffset = 0.5f + xOffsetNormalized;
        }       
        return xOffset;
    }
    
    public synchronized void addMovingListener(ZTouchMoveListener listener) {
        mListeners.add(listener);
    }
    
    private synchronized void dispatchMoving() {
        Iterator<ZTouchMoveListener> iterator = mListeners.iterator();
        while(iterator.hasNext())  {
            ((ZTouchMoveListener) iterator.next()).onTouchOffsetChanged(normalizePosition(mPosition + mPositionDelta));
        }
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
20.10.2013, 01:22
Ответы с готовыми решениями:

Анимация в живых обоях
Всем привет, у меня тут проблема, делаю живые обои с покадровой анимацией все сделал ок, все...

Как сделать волны на живых обоях?
Имеется фон с морем, как сделать волны на этом море?

Параллакс на CSS
Собственно вот он паралакс, и часть кода страницы, почему-то таблицы у меня отображаются корректно,...

Фон с параллакс эффектом
Привет всем, помогите разобраться. При уменьшении ширины браузера фон в разделах, уменьшается и...

0
20.10.2013, 01:22
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
20.10.2013, 01:22
Помогаю со студенческими работами здесь

Как прикрутить параллакс
Приветствую. Есть вот такая вёрстка. https://lnf353.github.io/architecture/ В дизайн-макете...

Прблема с параллакс эффектом
Здравствуйте, уважаемые коллеги! Делаю блок с параллакс эффектом. Но в макете имеются зигзаги до...

Параллакс в Internet explorer
Всем привет. Столкнулся с проблемой: использую плагин stellar.js, в нормальных браузерах все ок,...

Как сделать параллакс-фон
Я получаю координаты мыши и что с ними делать, то есть может какая то формула есть и что делать с...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru