Centering in a scroll view

How to center display group in the center of the scroll view? I can center group in another group called fakeScrollView and this is my desired outcome but I can’t do the same with a scroll view.

local widget = require("widget")
widget.setTheme("widget_theme_android")

_G.cx, _G.cy = display.contentCenterX, display.contentCenterY
_G.fullw, _G.fullh  = display.actualContentWidth, display.actualContentHeight

local scrollView = widget.newScrollView {
	x = cx,
	top = 50,
	height = fullh-100,
	width = fullw,
	horizontalScrollDisabled = true,
	verticalScrollDisabled = false,
	hideBackground = true,
	hideScrollBar = true
	}

--[[
local fakeScrollView = display.newGroup()
fakeScrollView.anchorChildren = true
fakeScrollView.x, fakeScrollView.y = cx, cy
--]]

local groupY = 0
for i = 1, 10 do
	local groupX = 0
	for j = 1, 4 do 
		local group = display.newGroup()
		scrollView:insert(group)
		group.x = groupX
		group.y = groupY
		groupX = groupX + 130

        local field = display.newRect(group, 0, 0, 100, 100)
		field:setFillColor(0 ,0 ,0.4)
	end
	groupY = groupY + 130
end

@gudrutis1,

It looks like you intend to place 4 “boxes” in a row, with 10 rows in the scrollview. How about doing these instead, to do the necessary grid placement?

local groupY = 65
for i = 1, 10 do
    local groupX = 130
    for j = 1, 4 do

It’s good, but it’s not perfect center, you can see how it differ on a different devices. For example, on iPad Pro it centered perfectly but on iPhone 4S it shifts slightly to the right. I see difference to other objects which is positioned in the center.

How you came up with a 130? I was looking for a perfect center math.

Looking at your code, and extend from there.

In any case, to make your code suitable for most devices, most scaling and with different “config.lua” dimensions, I would suggest using calculated variables to determine the grid positions for each “cell” or “box”, rather than using constant like “130”. Here is my suggested code. Please give it a try.

local numCols = 4
local numRows = 10
local width = fullw / ( numCols + 1 )
local groupY = width * 0.5 
for row = 1, numRows do
    local groupX = width
    for col = 1, numCols do 
        local group = display.newGroup()
        group.x = groupX
        group.y = groupY
        groupX = groupX + width
        local field = display.newRect( group, 0, 0, 100, 100 )
        field:setFillColor( 0, 0, 0.4 )
        scrollView:insert(group)
    end
    groupY = groupY + width
end
1 Like

Beautiful.Thank you.