Add Two Color Linear Gradient Backgrounds To View Elements In NativeScript

Since the css linear-gradient isn’t part of NativeScript core yet I went looking for the ability to do this online.  I found a git conversation over at https://github.com/NativeScript/NativeScript/issues/539 that discussed and shared some code.

The code doesn’t work on iOS as expected.  There were some typos in the code that need to be adjusted and wrong variables.  I’ve made those adjustments and you can copy below a functioning version.

I added it to a .js file in my /app directory called grad-bg.js.  Simply load this .js file into your page’s javascript code with:

var gradients = require("~/grad-bg.js");

Import the function via the require method.  Then in your page loaded function call the function on your view.  Make sure to set the view’s id in your xml file and use that id here as the second parameter:

https://gist.github.com/ChrisFlannagan/9fc4b8e2ef871208abcb7f15018cd6ec

Here’s the full javascript function for linearGradient

https://gist.github.com/ChrisFlannagan/5dd5ca61ac01b15cf60b87dda20beaba

Repo: https://github.com/ChrisFlannagan/nativescript-gradient-background

3 thoughts on “Add Two Color Linear Gradient Backgrounds To View Elements In NativeScript”

  1. Okay, I figured out that this doesn’t work whenever you’re using it in a “user control” type of format. I have a tab view, where I’m calling in seperate view files. I’m trying to apply the gradient in one of the view files that are embedded withing the tabview items.

    If I do everything in the main-page.xml and main-page.js files it works perfectly. Any idea how to get this to work in embedded views?

    1. Hmm, I’m not sure, if I have some time tonight I’ll toy around with it and get back to you. Thanks for the information though, very helpful to know.

Leave a Reply to Jeff Turner Cancel reply

Your email address will not be published.