Wandrille
Wandrille

Reputation: 6821

NativeScript - display element centered on tap

I have a problem with the css with NativeScript.

(The solution for a normal webapp is: translate(-50%, -50%) but this isn't working for Nativescript)

What I want: A circle centered where I touch.

What I get now: A circle NOT centered where I touch.

Do you have an Idea?

(When I have only one Circle of 300px, I can cheat with "translate(-40%, -40%)" but I'm looking for a solution for XXXpx)

=====

ANSWER: given by theOriginalJosh

I have to remove in my css:

And in my Script:

====

the Html

<AbsoluteLayout #container>
</AbsoluteLayout>

The component

@ViewChild('container') absoluteLayout: ElementRef;

public onTap(args: TouchGestureEventData) {
    if (args && args.action === 'down') {
        let xCoord = args.getX();
        let yCoord = args.getY();

        let label3 = new Label();
        label3.top = yCoord;
        label3.left = xCoord;
        label3.className = "circle three";

        let label4 = new Label();
        label4.top = yCoord;
        label4.left = xCoord;
        label4.className = "circle four";


        this.absoluteLayout.nativeElement.addChild(label3);
        this.absoluteLayout.nativeElement.addChild(label4);
    }
}

the css

.circle {
    color: blue ;
    border-style: solid;
    border-radius: 50%;
     transform: translate(-50%, -50%); 
}
.three {
    border-color: red;
    width: 50px;
    height: 50px;
    border-width: 20px;
} 
.four {
    border-color: blue;
    width: 300px;
    height: 300px;
    border-width: 20px;
} 

Upvotes: 0

Views: 161

Answers (1)

JoshSommer
JoshSommer

Reputation: 2618

Since you know the height and width of the circles you are placing on the page you can subtract half of those circles height and widths from the X and Y coordinates. that should center them.

public onTap(args: TouchGestureEventData) {
    if (args && args.action === 'down') {
    let xCoord = args.getX();
    let yCoord = args.getY();

    let label3 = new Label();
    label3.top = yCoord - 25;
    label3.left = xCoord - 25;
    label3.className = "circle three";

    let label4 = new Label();
    label4.top = yCoord - 150;
    label4.left = xCoord - 150;
    label4.className = "circle four";


    this.absoluteLayout.nativeElement.addChild(label3);
    this.absoluteLayout.nativeElement.addChild(label4);
}

}

you may want to check out the nativescript-ng2-windchimes app on Github it's about a year old but has many of the concepts you're trying to do. https://github.com/NathanWalker/nativescript-ng2-windchimes

Upvotes: 1

Related Questions