Reputation: 1315
I'm trying to make something similar to Paint in Unity.
I want to add functionality for zoom in/out. For this purpose, I've added paint area into into ScrollRect
and change localScale
of paint area on mouse wheel event.
var scrollDelta = Input.GetAxis("Mouse ScrollWheel");
var scale = _editableArea.localScale.x + scrollDelta;
_editableArea.localScale = new Vector3(scale, scale, scale);
There are also additional checks, but I omit them.
For now I'm trying to adjust scrollbars position, so after zoom mouse will be under the same element it was before. And... I stuck with formula to calculate new position of scrollbars. Probably, I reinvent the wheel and there is already a way to do this by native functions in Unity. Could you show me right way?
Thanks
Upvotes: 1
Views: 3184
Reputation: 1315
I've finally came to working solution, hope it'll help somebody:
var scale = _editableArea.localScale.x;
//mousePosition contains position of mouse inside scaled area in percentages
var mousePosition = (Vector2) (Input.mousePosition - _editableArea.position) - _editableArea.rect.position * scale;
mousePosition.x /= _editableArea.rect.width * scale;
mousePosition.y /= _editableArea.rect.height * scale;
var contentSize = _scrollRect.content.rect;
var shiftX = -scaleDelta* contentSize.width * (mousePosition.x - 0.5f);
var shiftY = -scaleDelta* contentSize.height * (mousePosition.y - 0.5f);
var currPos = _scrollRect.content.localPosition;
_scrollRect.content.localPosition = new Vector3(currPos.x + shiftX, currPos.y + shiftY, currPos.z);
Upvotes: 2