package de.cdietze.playn_util;

import playn.scene.Layer;
import pythagoras.f.IDimension;
import tripleplay.ui.Element;

import static com.google.common.base.Preconditions.checkArgument;

/**
 * Takes a {@link Layer} and scales it as big as possible while keeping its aspect ratio and its specified <i>world size</i>.
 */
public class ScaledElement extends Element<ScaledElement> {

    private static float maxScale(float aspectRatio, float viewWidth, float viewHeight) {
        checkArgument(aspectRatio > 0f);
        checkArgument(viewWidth > 0f);
        checkArgument(viewHeight > 0f);
        float maxWidthIfHeightRestricted = viewHeight * aspectRatio;
        float maxWidth = Math.min(viewWidth, maxWidthIfHeightRestricted);
        return maxWidth / viewWidth;
    }

    private final Layer worldLayer;
    private final IDimension worldSize;

    public ScaledElement(Layer layer, IDimension worldSize) {
        worldLayer = layer;
        this.worldSize = worldSize;
        this.layer.add(layer);
    }

    @Override
    protected LayoutData createLayoutData(float hintX, float hintY) {
        return new LayoutData() {
            @Override
            public void layout(float left, float top, float width, float height) {
                float ratio = worldSize.width() / worldSize.height();
                float scale = maxScale(ratio, width, height);
                worldLayer.setTranslation(left + width * .5f, top + height * .5f);
                worldLayer.setScale(scale * width / worldSize.width());
            }
        };
    }

    @Override
    protected Class<?> getStyleClass() {
        return ScaledElement.class;
    }
}

@@ -55,40 +55,8 @@
 er;%0A
-import pythagoras.f.IDimension;%0A
 impo
@@ -515,48 +515,111 @@
 %3E 0f
-);%0A        checkArgument(viewHeight %3E 0f
+ && viewHeight %3E 0f, %22view width and height must be greater than 0, are you using a stretching layout?%22
 );%0A 
@@ -843,48 +843,8 @@
 yer;
-%0A    private final IDimension worldSize;
 %0A%0A  
@@ -881,30 +881,8 @@
 ayer
-, IDimension worldSize
 ) %7B%0A
@@ -921,34 +921,95 @@
     
-this.worldSize = worldSize
+checkArgument(layer.width() %3E 0f && layer.height() %3E 0f, %22The layer must have a size.%22)
 ;%0A  
@@ -1298,28 +1298,29 @@
 atio = world
-Size
+Layer
 .width() / w
@@ -1323,20 +1323,21 @@
  / world
-Size
+Layer
 .height(
@@ -1545,12 +1545,13 @@
 orld
-Size
+Layer
 .wid

Update ScaledElement - use world.size from layer not from extra parameter