SwiftUI reusable view - button

i have a view "TopTabBar" and i use it in two different screens. but in one screen there should be 2 buttons, and in the other 4.
in the usual swift, I would create a function in this TopTabBar, with which I would add buttons to the Stack, and create them from where I use it. but in SwiftUI I can't do that.
How can I get the screen reused and filled with the right amount of buttons from the outside?
import SwiftUI
struct TopBar: View {
var firstViewTitle: String
var secondViewTitle: String
var thirdViewTitle: String?
var fourthViewTitle: String?
#Binding var tabIndex: Int
var body: some View {
HStack(spacing: 0) {
TabBarButton(text: firstViewTitle, isSelected: .constant(tabIndex == 0))
.onTapGesture { onButtonTapped(index: 0) }
TabBarButton(text: secondViewTitle, isSelected: .constant(tabIndex == 1))
.onTapGesture { onButtonTapped(index: 1) }
TabBarButton(text: thirdViewTitle ?? "", isSelected: .constant(tabIndex == 2))
.onTapGesture { onButtonTapped(index: 2) }
TabBarButton(text: fourthViewTitle ?? "", isSelected: .constant(tabIndex == 3))
.onTapGesture { onButtonTapped(index: 3) }
}
.border(width: 1, edges: [.bottom], color: .lightGrey)
.frame(width: UIScreen.screenWidth, height: 50, alignment: .center)
}
private func onButtonTapped(index: Int) {
withAnimation { tabIndex = index }
}
}
struct TabBarButton: View {
let text: String
#Binding var isSelected: Bool
var body: some View {
Text(text)
.foregroundColor(isSelected ? .black : .gray)
.fontWeight(isSelected ? .heavy : .regular)
.padding(.bottom, 10)
.border(width: isSelected ? 2 : 0, edges: [.bottom], color: .black)
.frame(width: UIScreen.screenWidth/4, height: 50, alignment: .center)
.background(Color.random)
}
}
struct Usable: View {
#State var tabIndex = 0
var body: some View {
NavigationView {
ZStack {
if tabIndex == 1 {
debugPring("xxx")
}
VStack {
TopBar(firstViewTitle: "first", secondViewTitle: "second", thirdViewTitle: "third", fourthViewTitle: "fourth" ,tabIndex: $tabIndex).padding(.top, 20)
if tabIndex == 0 {
debugPrint("xxx")
}
Spacer()
}
}
.navigationBarHidden(true)
}.accentColor(Color.black)
}
}

Actually there are many options, but with your current design it is possible just to make them conditional, like
HStack(spacing: 0) {
TabBarButton(text: firstViewTitle, isSelected: .constant(tabIndex == 0))
.onTapGesture { onButtonTapped(index: 0) }
TabBarButton(text: secondViewTitle, isSelected: .constant(tabIndex == 1))
.onTapGesture { onButtonTapped(index: 1) }
if let title = thirdViewTitle {
TabBarButton(text: title, isSelected: .constant(tabIndex == 2))
.onTapGesture { onButtonTapped(index: 2) }
}
if let title = fourthViewTitle {
TabBarButton(text: title, isSelected: .constant(tabIndex == 3))
.onTapGesture { onButtonTapped(index: 3) }
}
}

Related

Swift UICollectionViewCell Item Mixing... Video of the problem is available

My problem video: https://streamable.com/2vrdbu
As you move around the "Collection View" the objects move around and the assignment doesn't work properly.
I tried many methods, but I could not achieve successful results.
Code blocks:
UIViewController:
class BeadsViewController: UIViewController {
private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 10
layout.sectionInset = .init(top: 0, left: 0, bottom: 0, right: 0)
return layout
}()
private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(BeadsCell.self, forCellWithReuseIdentifier: BeadsCell.reuseID)
collectionView.backgroundColor = .clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
return collectionView
}()
Extension for CollectionView
Extension View Controller: (UICollectionViewCell Delegate etc.)
extension BeadsViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return beadsList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = collectionView.dequeueReusableCell(withReuseIdentifier: BeadsCell.reuseID, for: indexPath) as! BeadsCell
incomingIndex = indexPath.item + 1
let beads = beadsList[indexPath.item]
item.setGenerate(item: Beads(imageName: beads.imageName, isPremium: beads.isPremium))
return item
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width: CGFloat = (collectionViewWidth - 38) / CGFloat(3)
let height: CGFloat
switch screenHeight {
case 667: // SE 2nd gen, 8, 7, 6s, 6
height = (160 * screenHeight) / 926
case 736: // 8 plus
height = (150 * screenHeight) / 926
default:
height = (163 * screenHeight) / 926 // 13 pro max - 12 pro max
}
return CGSize(width: width, height: height)
}
}
Cell:
class BeadsCell: UICollectionViewCell {
static let reuseID = "beadsCell"
lazy var backgroundArea: UIImageView = {
let bgArea = UIImageView()
bgArea.layer.cornerRadius = 10
bgArea.image = UIImage(named: "lockBeadBG")?.withRenderingMode(.alwaysOriginal)
return bgArea
}()
lazy var imageArea: UIImageView = {
let imageArea = UIImageView()
imageArea.contentMode = .scaleAspectFit
return imageArea
}()
lazy var lockImage: UIImageView = {
let imageArea = UIImageView()
imageArea.contentMode = .scaleAspectFit
imageArea.image = UIImage(named: "lockImage")?.withRenderingMode(.alwaysOriginal)
return imageArea
}()
lazy var openImage: UIImageView = {
let imageArea = UIImageView()
imageArea.contentMode = .scaleAspectFit
imageArea.image = UIImage(named: "unlcokBtn")?.withRenderingMode(.alwaysOriginal)
return imageArea
}()
lazy var openText: UILabel = {
let label = UILabel()
label.text = "Open"
label.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
label.font = UIFont(name: "CeraPro-Bold", size: 15.2)
return label
}()
func setGenerate(item: Beads) {
if(item.isPremium == false){
imageArea.image = UIImage(named: item.imageName!)?.withRenderingMode(.alwaysOriginal)
} else if (item.isPremium == true) {
imageArea.image = UIImage(named: item.imageName!)?.withRenderingMode(.alwaysOriginal)
}
}
lazy var screenHeight = UIScreen.main.bounds.height
lazy var screenWidth = UIScreen.main.bounds.width
func beadsCellLayout(){
addSubview(backgroundArea)
if (beadsList[incomingIndex].isPremium == false) {
backgroundArea.anchor(top: contentView.topAnchor, bottom: contentView.bottomAnchor, leading: contentView.leadingAnchor, trailing: contentView.trailingAnchor, size: .init(width: (120 * screenWidth / 428), height: (163 * screenHeight / 926)))
backgroundArea.addSubview(imageArea)
imageArea.anchor(top: nil, bottom: nil, leading: nil, trailing: nil, size: .init(width: (75 * screenWidth / 428 ), height: (75 * screenHeight / 926)))
imageArea.centerXAnchor.constraint(equalTo: backgroundArea.centerXAnchor).isActive = true
imageArea.centerYAnchor.constraint(equalTo: backgroundArea.centerYAnchor).isActive = true
} else {
backgroundArea.anchor(top: contentView.topAnchor, bottom: contentView.bottomAnchor, leading: contentView.leadingAnchor, trailing: contentView.trailingAnchor, size: .init(width: (120 * screenWidth / 428), height: (163 * screenHeight / 926)))
backgroundArea.addSubview(imageArea)
imageArea.anchor(top: backgroundArea.topAnchor, bottom: nil, leading: nil, trailing: nil, padding: .init(top: 25, left: 0, bottom: 0, right: 0))
imageArea.centerXAnchor.constraint(equalTo: backgroundArea.centerXAnchor).isActive = true
backgroundArea.addSubview(lockImage)
lockImage.anchor(top: nil, bottom: nil, leading: imageArea.leadingAnchor, trailing: nil, padding: .init(top: 0, left: (22 * screenWidth / 428), bottom: 0, right: 0))
lockImage.centerYAnchor.constraint(equalTo: imageArea.centerYAnchor).isActive = true
backgroundArea.addSubview(openImage)
openImage.anchor(top: nil, bottom: backgroundArea.bottomAnchor, leading: nil, trailing: nil, padding: .init(top: 0, left: 0, bottom: 10, right: 0))
openImage.centerXAnchor.constraint(equalTo: backgroundArea.centerXAnchor).isActive = true
openImage.addSubview(openText)
openText.anchor(top: openImage.topAnchor, bottom: nil, leading: openImage.leadingAnchor, trailing: nil, padding: .init(top: 13, left: 40, bottom: 0, right: 0))
}
}
override init(frame: CGRect) {
super.init(frame: frame)
beadsCellLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*override func prepareForReuse() {
//super.prepareForReuse()
backgroundArea.image = nil
imageArea.image = nil
lockImage.image = nil
openImage.image = nil
openText.text = nil
}*/
}
In this case, you should use two different cells for the collectionview.
One for current cells and one for premium ones

How to refer css class in a component.ts file

I am trying to create a neural net visualization using d3.js in Angular 7. I have successfully created the nodes but the links are not appearing. The code refers to a css class defined in the components css file. What am I doing wrong?
Shown below is the code responsible for link creation:
// draw links
var link:any = svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link")
.attr("x1", function(d) { return nodes[d.source].x; })
.attr("y1", function(d) { return nodes[d.source].y; })
.attr("x2", function(d) { return nodes[d.target].x; })
.attr("y2", function(d) { return nodes[d.target].y; })
.style("stroke-width", function(d) {return Math.sqrt(d.value); });
css :
.link {
stroke: #999;
stroke-opacity: .6;
}
shown below is the code of my complete neural.component.ts file (which contains the above typescript code).
import { Component, OnInit,Input } from '#angular/core';
import {select,schemeCategory10,scaleOrdinal} from 'd3';
import { angularMath } from 'angular-ts-math';
declare var $:any;
#Component({
selector: 'app-neuralcanvas',
templateUrl: './neuralcanvas.component.html',
styleUrls: ['./neuralcanvas.component.css']
})
export class NeuralcanvasComponent implements OnInit {
// color = scaleOrdinal().range(schemeCategory10)
inputLayerHeight = 4;
outputLayerHeight=5;
hiddenLayersDepths =[3,4];
hiddenLayersCount =2;
nodeSize = 17;
width :any = 500 ;
height = 400;
constructor() { }
ngOnInit() {
this.draw()
}
draw() {
console.log('in draw')
if (!select("svg")[0]) {
} else {
//clear d3
select('svg').remove();
}
var svg = select("#neuralNet").append("svg")
.attr("width", this.width)
.attr("height", this.height);
var networkGraph : any = this.buildNodeGraph();
//buildNodeGraph();
this.drawGraph(networkGraph, svg);
}
buildNodeGraph() {
var newGraph:any = {
"nodes": []
};
//construct input layer
var newFirstLayer: any = [];
for (var i = 0; i < this.inputLayerHeight; i++) {
var newTempLayer1 :any = {"label": "i"+i, "layer": 1};
newFirstLayer.push(newTempLayer1);
}
//construct hidden layers
var hiddenLayers:any = [];
for (var hiddenLayerLoop = 0; hiddenLayerLoop < this.hiddenLayersCount; hiddenLayerLoop++) {
var newHiddenLayer:any = [];
//for the height of this hidden layer
for (var i = 0; i < this.hiddenLayersDepths[hiddenLayerLoop]; i++) {
var newTempLayer2:any = {"label": "h"+ hiddenLayerLoop + i, "layer": (hiddenLayerLoop+2)};
newHiddenLayer.push(newTempLayer2);
}
hiddenLayers.push(newHiddenLayer);
}
//construct output layer
var newOutputLayer:any = [];
for (var i = 0; i < this.outputLayerHeight; i++) {
var newTempLayer3 = {"label": "o"+i, "layer": this.hiddenLayersCount + 2};
newOutputLayer.push(newTempLayer3);
}
//add to newGraph
var allMiddle:any = newGraph.nodes.concat.apply([], hiddenLayers);
newGraph.nodes = newGraph.nodes.concat(newFirstLayer, allMiddle, newOutputLayer );
return newGraph;
}
drawGraph(networkGraph, svg) {
var color = scaleOrdinal(schemeCategory10);
var graph = networkGraph;
var nodes = graph.nodes;
// get network size
var netsize = {};
nodes.forEach(function (d) {
if(d.layer in netsize) {
netsize[d.layer] += 1;
} else {
netsize[d.layer] = 1;
}
d["lidx"] = netsize[d.layer];
});
// calc distances between nodes
var largestLayerSize = Math.max.apply(
null, Object.keys(netsize).map(function (i) { return netsize[i]; }));
var xdist = this.width / Object.keys(netsize).length,
ydist = (this.height-15) / largestLayerSize;
// create node locations
nodes.map(function(d) {
d["x"] = (d.layer - 0.5) * xdist;
d["y"] = ( ( (d.lidx - 0.5) + ((largestLayerSize - netsize[d.layer]) /2 ) ) * ydist )+10 ;
});
// autogenerate links
var links:any = [];
nodes.map(function(d, i) {
for (var n in nodes) {
if (d.layer + 1 == nodes[n].layer) {
links.push({"source": parseInt(i), "target": parseInt(n), "value": 1}) }
}
}).filter(function(d) { return typeof d !== "undefined"; });
// draw links
var link:any = svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link")
.attr("x1", function(d) { return nodes[d.source].x; })
.attr("y1", function(d) { return nodes[d.source].y; })
.attr("x2", function(d) { return nodes[d.target].x; })
.attr("y2", function(d) { return nodes[d.target].y; })
.style("stroke-width", function(d) {return Math.sqrt(d.value); });
// draw nodes
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; }
);
var circle = node.append("circle")
.attr("class", "node")
.attr("r", this.nodeSize)
.style("fill", function(d) { return color(d.layer); });
node.append("text")
.attr("dx", "-.35em")
.attr("dy", ".35em")
.attr("font-size", ".6em")
.text(function(d) { return d.label; });
}
}
the code of the neural.component.css:
.link {
stroke: #999;
stroke-opacity: .6;
}
The current output lokks like this:
I want to show the inks as:
As you'll see the generation code is already there I want to know how to refer the class to get the links appearing in Angular 7

Resizing does not work in paperjs 0.11.8 but works for 0.9.25

I am trying to resize a rectangle in paper.js. I am able to do it for older versions of paperjs (like 0.9.25) but it is not working for the latest version 0.11.8. I am not sure why this is happening, any help would be highly appreciated.
Here is the Sketch link, you may select the version to 0.9.25 where it works and 0.11.8 where it doesnt work.
Sketch
Here is my code:
var hitOptions = {
segments: true,
stroke: true,
fill: true,
tolerance: 1
};
project.currentStyle = {
fillColor: 'green',
strokeColor: 'black'
};
var rect_a = new Path.Rectangle(new Point(50, 50), 50);
var segment, path, hitType;
var clickPos = null;
var movePath = false;
var minHeight = 1;
var minWidth = 1;
function onMouseDown(event) {
segment = path = null;
var hitResult = project.hitTest(event.point, hitOptions);
if (!hitResult)
return;
hitType = hitResult.type;
if (event.modifiers.shift) {
if (hitResult.type == 'segment') {
hitResult.segment.remove();
};
return;
}
if (hitResult) {
path = hitResult.item;
if (hitResult.type == 'segment') {
segment = hitResult.segment;
}
}
movePath = hitResult.type == 'fill';
if (movePath) {
project.activeLayer.addChild(hitResult.item);
}
clickPos = checkHitPosition(event);
}
function onMouseMove(event) {
changeCursor(event);
project.activeLayer.selected = false;
if (event.item)
event.item.selected = true;
}
function onMouseDrag(event) {
if (hitType == "stroke" || hitType == "segment") {
resizeRectangle(path, event);
} else {
path.position += event.delta;
}
}
function resizeRectangle(path, event) {
switch(clickPos) {
case "SE" :
resizeBottom(path, event);
resizeRight(path, event);
break;
case "NE" :
resizeTop(path, event);
resizeRight(path, event);
break;
case "SW" :
resizeBottom(path, event);
resizeLeft(path, event);
break;
case "NW" :
resizeTop(path, event);
resizeLeft(path, event);
break;
case "S" :
resizeBottom(path, event);
break;
case "N" :
resizeTop(path, event);
break;
case "E" :
resizeRight(path, event);
break;
case "W" :
resizeLeft(path, event);
break;
}
}
function resizeTop(path, event) {
if(path.bounds.height >= minHeight) {
var adj = Math.min(event.delta.y, path.bounds.height-minHeight);
path.bounds.top += adj;
}
}
function resizeBottom(path, event) {
if(path.bounds.height >= minHeight) {
path.bounds.bottom += event.delta.y;
}
}
function resizeLeft(path, event) {
if(path.bounds.width >= minWidth) {
path.bounds.left += event.delta.x;
}
}
function resizeRight(path, event) {
if(path.bounds.width >= minWidth) {
path.bounds.right += event.delta.x;
}
}
function checkHitPosition(event) {
var hitResult = project.hitTest(event.point, hitOptions);
var clickPosition = null;
if (hitResult) {
if (hitResult.type == 'stroke' || hitResult.type == 'segment') {
var bounds = hitResult.item.bounds;
var point = hitResult.point;
if (bounds.top == point.y) {
clickPosition = "N";
}
if (bounds.bottom == point.y) {
clickPosition = "S";
}
if (bounds.left == point.x) {
clickPosition = "W";
}
if (bounds.right == point.x) {
clickPosition = "E";
}
if (bounds.top == point.y && bounds.left == point.x) {
clickPosition = "NW";
}
if (bounds.top == point.y && bounds.right == point.x) {
clickPosition = "NE";
}
if (bounds.bottom == point.y && bounds.left == point.x) {
clickPosition = "SW";
}
if (bounds.bottom == point.y && bounds.right == point.x) {
clickPosition = "SE";
}
} else {
clickPosition = "C";
}
}
return clickPosition;
};
function changeCursor(event) {
var hitPosition = checkHitPosition(event);
if(hitPosition == null ) {
document.body.style.cursor = "auto";
} else {
if (hitPosition == "C") {
document.body.style.cursor = "all-scroll";
} else {
document.body.style.cursor = hitPosition + "-resize";
}
}
}
helloworld,
If you want to resize/scale your path, I recommend using the Path.scalemethod (http://paperjs.org/reference/item/#scale-hor-ver).
To apply this on your example, replace your current resizing methods with:
function resizeTop(path, event) {
if(path.bounds.height >= minHeight) {
var relH = (event.point.y - (path.bounds.bottomCenter.y)) / path.bounds.height;
path.scale(1, -relH, path.bounds.bottomCenter)
}
}
function resizeBottom(path, event) {
if(path.bounds.height >= minHeight) {
var relH = (event.point.y - (path.bounds.topCenter.y)) / path.bounds.height;
path.scale(1, relH, path.bounds.topCenter)
}
}
function resizeLeft(path, event) {
if(path.bounds.width >= minWidth) {
var relW = (event.point.x - (path.bounds.rightCenter.x)) / path.bounds.width;
path.scale(-relW, 1, path.bounds.rightCenter)
}
}
function resizeRight(path, event) {
if(path.bounds.width >= minWidth) {
var relW = (event.point.x - (path.bounds.leftCenter.x)) / path.bounds.width;
path.scale(relW, 1, path.bounds.leftCenter)
}
}
Have a nice day!
-- edit --
I remade your sketch and replaced the code, sketch, which works with every version.

Ext5 : Pie chart being cut off when hovering

I am using Ext5 pie chart.
When I mouse hover the pie chart it is being cut off.
The code for the pie chart is given below.
{
type: 'pie',
field: 'item1',
renderer: function(sprite, config, rendererData, index) {
var record = rendererData.store.getAt(rendererData.series.sprites.indexOf(sprite));
var name = record.get('name');
if(chartObj.baseThemeColors[name]){
var color = chartObj.baseThemeColors[name];
} else {
color = chartObj.getRandomColor();
chartObj.baseThemeColors[name] = color;
}
return Ext.apply(rendererData, {
fill: color
});
return rendererData;
},
subStyle: {
strokeStyle: 'white',
insertPadding: '50',
lineWidth: '0.5'
},
highlight: {
segment: {
margin: 20
}
},
tooltip: {
trackMouse: true,
width: 'auto',
height: 40,
renderer: function(storeItem, item) {
//calculate percentage.
var total = 0;
var idType = storeItem.get('type');
chartStore.each(function(rec) {
total += rec.get('item1');
});
if(storeItem.get('item1') == 0){
this.setTitle('');
}else {
var pct = ((storeItem.get('item1')/total) * 100).toFixed(0);
var tipText = pct + '% (' + storeItem.get('item1') + ' of ' + total + ')<br/>' + storeItem.get('name')
this.setTitle(tipText);
}
}
},
label: {
field: 'name',
display: 'rotate',
font: '14px Arial',
renderer: function(text, sprite, config, rendererData, index){
var item = rendererData.store.getAt(index);
var total = 0,
idType = item.get('type'),
labelText = "";
chartStore.each(function(rec) {
total += rec.get('item1');
});
if(item.get('item1') == 0){
labelText = '';
} else {
var pct = ((item.get('item1') / total) * 100).toFixed(0);
if(pct>1){
labelText = text + ' ' + pct+'%';
} else {
labelText = '';
}
}
return labelText;
}
}
}
Here is the image of the issue.
As you can see top of the 'negative' slice is being cut off when mouse hovering. And I cannot remove that slice moving animation when hovering.
Is there any solution for this?
Thanks in advance.
Try setting
trackMouse: false
Instead of
trackMouse: true

Set fixed width to Nivo Slider

I've installed Nivo Slider using the code from the demo included in the free download.
All of the images I am including in the slider are 800 pixels wide.
However, they are being resized to 1440 pixels wide. Extra code is being inserted:
<img src="images/bar.jpg" data-thumb="images/bar.jpg" alt="" title="" style="display: none; width: 1440px;">
I have searched the CSS and JS and can find no mention of 1440.
Where is this width being set?
Nivo Slider is responsive by default, if you want to limit the sliders width, use the below class in your CSS
.slider-wrapper.theme-default {
width: 800px; /* Desired width */
}
The above will work if you are using default theme of nivo slider, if you are using some other theme, than simply change the .theme-default to theme specific class which is assigned to the slider wrapper.
Use my custom nivo script code
/*
* jQuery Nivo Slider v2.5.1
* http://nivo.dev7studios.com
*
* Copyright 2011, Gilbert Pellegrom
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* March 2010
*/
(function($) {
var NivoSlider = function(element, options) {
var settings = $.extend({}, $.fn.nivoSlider.defaults, options);
var vars = {
currentSlide : 0,
currentImage : '',
totalSlides : 0,
randAnim : '',
running : false,
paused : false,
stop : false
};
var slider = $(element);
slider.data('nivo:vars', vars);
slider.css('position', 'relative');
slider.addClass('nivoSlider');
var kids = slider.children();
kids.each(function() {
var child = $(this);
var link = '';
if (!child.is('img')) {
if (child.is('a')) {
child.addClass('nivo-imageLink');
link = child;
}
child = child.find('img:first');
}
var childWidth = child.width();
if (childWidth == 0)
childWidth = child.attr('width');
var childHeight = child.height();
if (childHeight == 0)
childHeight = child.attr('height');
if (childWidth > slider.width()) {
slider.width(childWidth);
}
if (childHeight > slider.height()) {
slider.height(childHeight);
}
if (link != '') {
link.css('display', 'none');
}
child.css('display', 'none');
vars.totalSlides++;
});
if (settings.startSlide > 0) {
if (settings.startSlide >= vars.totalSlides)
settings.startSlide = vars.totalSlides - 1;
vars.currentSlide = settings.startSlide;
}
if ($(kids[vars.currentSlide]).is('img')) {
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
if ($(kids[vars.currentSlide]).is('a')) {
$(kids[vars.currentSlide]).css('display', 'block');
}
slider.css({
'background' : 'url("' + vars.currentImage.attr('src') + '") no-repeat',
'background-size' : settings.backgroundSize
});
slider.append($('<div class="nivo-caption"><p></p></div>').css({
display : 'none',
opacity : settings.captionOpacity
}));
var processCaption = function(settings) {
var nivoCaption = $('.nivo-caption', slider);
if (vars.currentImage.attr('title') != '') {
var title = vars.currentImage.attr('title');
if (title.substr(0, 1) == '#')
title = $(title).html();
if (nivoCaption.css('display') == 'block') {
nivoCaption.find('p').fadeOut(settings.animSpeed, function() {
$(this).html(title);
$(this).fadeIn(settings.animSpeed);
});
} else {
nivoCaption.find('p').html(title);
}
nivoCaption.fadeIn(settings.animSpeed);
} else {
nivoCaption.fadeOut(settings.animSpeed);
}
}
processCaption(settings);
var timer = 0;
if (!settings.manualAdvance && kids.length > 1) {
timer = setInterval(function() {
nivoRun(slider, kids, settings, false);
}, settings.pauseTime);
}
if (settings.directionNav) {
slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">' + settings.prevText + '</a><a class="nivo-nextNav">' + settings.nextText + '</a></div>');
if (settings.directionNavHide) {
$('.nivo-directionNav', slider).hide();
slider.hover(function() {
$('.nivo-directionNav', slider).show();
}, function() {
$('.nivo-directionNav', slider).hide();
});
}
$('a.nivo-prevNav', slider).live('click', function() {
if (vars.running)
return false;
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
});
$('a.nivo-nextNav', slider).live('click', function() {
if (vars.running)
return false;
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
});
}
if (settings.controlNav) {
var nivoControl = $('<div class="nivo-controlNav"></div>');
slider.append(nivoControl);
for (var i = 0; i < kids.length; i++) {
if (settings.controlNavThumbs) {
var child = kids.eq(i);
if (!child.is('img')) {
child = child.find('img:first');
}
if (settings.controlNavThumbsFromRel) {
nivoControl.append('<a class="nivo-control" rel="' + i + '"><img src="' + child.attr('rel') + '" alt="" /></a>');
} else {
nivoControl.append('<a class="nivo-control" rel="' + i + '"><img src="' + child.attr('src').replace(settings.controlNavThumbsSearch, settings.controlNavThumbsReplace) + '" alt="" /></a>');
}
} else {
nivoControl.append('<a class="nivo-control" rel="' + i + '">' + (i + 1) + '</a>');
}
}
$('.nivo-controlNav a:eq(' + vars.currentSlide + ')', slider).addClass('active');
$('.nivo-controlNav a', slider).live('click', function() {
if (vars.running)
return false;
if ($(this).hasClass('active'))
return false;
clearInterval(timer);
timer = '';
slider.css({
'background' : 'url("' + vars.currentImage.attr('src') + '") no-repeat',
'background-size' : settings.backgroundSize
});
vars.currentSlide = $(this).attr('rel') - 1;
nivoRun(slider, kids, settings, 'control');
});
}
if (settings.keyboardNav) {
$(window).keypress(function(event) {
if (event.keyCode == '37') {
if (vars.running)
return false;
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
}
if (event.keyCode == '39') {
if (vars.running)
return false;
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
}
});
}
if (settings.pauseOnHover) {
slider.hover(function() {
vars.paused = true;
clearInterval(timer);
timer = '';
}, function() {
vars.paused = false;
if (timer == '' && !settings.manualAdvance) {
timer = setInterval(function() {
nivoRun(slider, kids, settings, false);
}, settings.pauseTime);
}
});
}
slider.bind('nivo:animFinished', function() {
vars.running = false;
$(kids).each(function() {
if ($(this).is('a')) {
$(this).css('display', 'none');
}
});
if ($(kids[vars.currentSlide]).is('a')) {
$(kids[vars.currentSlide]).css('display', 'block');
}
if (timer == '' && !vars.paused && !settings.manualAdvance) {
timer = setInterval(function() {
nivoRun(slider, kids, settings, false);
}, settings.pauseTime);
}
settings.afterChange.call(this);
});
var createSlices = function(slider, settings, vars) {
for (var i = 0; i < settings.slices; i++) {
var sliceWidth = Math.round(slider.width() / settings.slices);
if (i == settings.slices - 1) {
slider.append($('<div class="nivo-slice"></div>').css({
left : (sliceWidth * i) + 'px',
width : (slider.width() - (sliceWidth * i)) + 'px',
height : '0px',
opacity : '0',
background : 'url("' + vars.currentImage.attr('src') + '") no-repeat -' + ((sliceWidth + (i * sliceWidth)) - sliceWidth) + 'px 0%',
'background-size': settings.backgroundSize
}));
} else {
slider.append($('<div class="nivo-slice"></div>').css({
left : (sliceWidth * i) + 'px',
width : sliceWidth + 'px',
height : '0px',
opacity : '0',
background : 'url("' + vars.currentImage.attr('src') + '") no-repeat -' + ((sliceWidth + (i * sliceWidth)) - sliceWidth) + 'px 0%',
'background-size': settings.backgroundSize
}));
}
}
}
var createBoxes = function(slider, settings, vars) {
var boxWidth = Math.round(slider.width() / settings.boxCols);
var boxHeight = Math.round(slider.height() / settings.boxRows);
for (var rows = 0; rows < settings.boxRows; rows++) {
for (var cols = 0; cols < settings.boxCols; cols++) {
if (cols == settings.boxCols - 1) {
slider.append($('<div class="nivo-box"></div>').css({
opacity : 0,
left : (boxWidth * cols) + 'px',
top : (boxHeight * rows) + 'px',
width : (slider.width() - (boxWidth * cols)) + 'px',
height : boxHeight + 'px',
background : 'url("' + vars.currentImage.attr('src') + '") no-repeat -' + ((boxWidth + (cols * boxWidth)) - boxWidth) + 'px -' + ((boxHeight + (rows * boxHeight)) - boxHeight) + 'px',
'background-size': settings.backgroundSize
}));
} else {
slider.append($('<div class="nivo-box"></div>').css({
opacity : 0,
left : (boxWidth * cols) + 'px',
top : (boxHeight * rows) + 'px',
width : boxWidth + 'px',
height : boxHeight + 'px',
background : 'url("' + vars.currentImage.attr('src') + '") no-repeat -' + ((boxWidth + (cols * boxWidth)) - boxWidth) + 'px -' + ((boxHeight + (rows * boxHeight)) - boxHeight) + 'px',
'background-size': settings.backgroundSize
}));
}
}
}
}
var nivoRun = function(slider, kids, settings, nudge) {
var vars = slider.data('nivo:vars');
if (vars && (vars.currentSlide == vars.totalSlides - 1)) {
settings.lastSlide.call(this);
}
if ((!vars || vars.stop) && !nudge)
return false;
settings.beforeChange.call(this);
if (!nudge) {
slider.css({'background':'url("' + vars.currentImage.attr('src') + '") no-repeat','background-size': settings.backgroundSize });
} else {
if (nudge == 'prev') {
slider.css({'background':'url("' + vars.currentImage.attr('src') + '") no-repeat','background-size': settings.backgroundSize });
}
if (nudge == 'next') {
slider.css({'background':'url("' + vars.currentImage.attr('src') + '") no-repeat','background-size': settings.backgroundSize });
}
}
vars.currentSlide++;
if (vars.currentSlide == vars.totalSlides) {
vars.currentSlide = 0;
settings.slideshowEnd.call(this);
}
if (vars.currentSlide < 0)
vars.currentSlide = (vars.totalSlides - 1);
if ($(kids[vars.currentSlide]).is('img')) {
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
if (settings.controlNav) {
$('.nivo-controlNav a', slider).removeClass('active');
$('.nivo-controlNav a:eq(' + vars.currentSlide + ')', slider).addClass('active');
}
processCaption(settings);
$('.nivo-slice', slider).remove();
$('.nivo-box', slider).remove();
if (settings.effect == 'random') {
var anims = new Array('sliceDownRight', 'sliceDownLeft', 'sliceUpRight', 'sliceUpLeft', 'sliceUpDown', 'sliceUpDownLeft', 'fold', 'fade', 'boxRandom', 'boxRain', 'boxRainReverse', 'boxRainGrow', 'boxRainGrowReverse');
vars.randAnim = anims[Math.floor(Math.random() * (anims.length + 1))];
if (vars.randAnim == undefined)
vars.randAnim = 'fade';
}
if (settings.effect.indexOf(',') != -1) {
var anims = settings.effect.split(',');
vars.randAnim = anims[Math.floor(Math.random() * (anims.length))];
if (vars.randAnim == undefined)
vars.randAnim = 'fade';
}
vars.running = true;
if (settings.effect == 'sliceDown' || settings.effect == 'sliceDownRight' || vars.randAnim == 'sliceDownRight' || settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft') {
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var slices = $('.nivo-slice', slider);
if (settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft')
slices = $('.nivo-slice', slider)._reverse();
slices.each(function() {
var slice = $(this);
slice.css({
'top' : '0px'
});
if (i == settings.slices - 1) {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if (settings.effect == 'sliceUp' || settings.effect == 'sliceUpRight' || vars.randAnim == 'sliceUpRight' || settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft') {
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var slices = $('.nivo-slice', slider);
if (settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft')
slices = $('.nivo-slice', slider)._reverse();
slices.each(function() {
var slice = $(this);
slice.css({
'bottom' : '0px'
});
if (i == settings.slices - 1) {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if (settings.effect == 'sliceUpDown' || settings.effect == 'sliceUpDownRight' || vars.randAnim == 'sliceUpDown' || settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft') {
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var v = 0;
var slices = $('.nivo-slice', slider);
if (settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft')
slices = $('.nivo-slice', slider)._reverse();
slices.each(function() {
var slice = $(this);
if (i == 0) {
slice.css('top', '0px');
i++;
} else {
slice.css('bottom', '0px');
i = 0;
}
if (v == settings.slices - 1) {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
v++;
});
} else if (settings.effect == 'fold' || vars.randAnim == 'fold') {
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
$('.nivo-slice', slider).each(function() {
var slice = $(this);
var origWidth = slice.width();
slice.css({
top : '0px',
height : '100%',
width : '0px'
});
if (i == settings.slices - 1) {
setTimeout(function() {
slice.animate({
width : origWidth,
opacity : '1.0'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
slice.animate({
width : origWidth,
opacity : '1.0'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if (settings.effect == 'fade' || vars.randAnim == 'fade') {
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height' : '100%',
'width' : slider.width() + 'px'
});
firstSlice.animate({
opacity : '1.0'
}, (settings.animSpeed * 2), '', function() {
slider.trigger('nivo:animFinished');
});
} else if (settings.effect == 'slideInRight' || vars.randAnim == 'slideInRight') {
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height' : '100%',
'width' : '0px',
'opacity' : '1'
});
firstSlice.animate({
width : slider.width() + 'px'
}, (settings.animSpeed * 2), '', function() {
slider.trigger('nivo:animFinished');
});
} else if (settings.effect == 'slideInLeft' || vars.randAnim == 'slideInLeft') {
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height' : '100%',
'width' : '0px',
'opacity' : '1',
'left' : '',
'right' : '0px'
});
firstSlice.animate({
width : slider.width() + 'px'
}, (settings.animSpeed * 2), '', function() {
firstSlice.css({
'left' : '0px',
'right' : ''
});
slider.trigger('nivo:animFinished');
});
} else if (settings.effect == 'boxRandom' || vars.randAnim == 'boxRandom') {
createBoxes(slider, settings, vars);
var totalBoxes = settings.boxCols * settings.boxRows;
var i = 0;
var timeBuff = 0;
var boxes = shuffle($('.nivo-box', slider));
boxes.each(function() {
var box = $(this);
if (i == totalBoxes - 1) {
setTimeout(function() {
box.animate({
opacity : '1'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
box.animate({
opacity : '1'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 20;
i++;
});
} else if (settings.effect == 'boxRain' || vars.randAnim == 'boxRain' || settings.effect == 'boxRainReverse' || vars.randAnim == 'boxRainReverse' || settings.effect == 'boxRainGrow' || vars.randAnim == 'boxRainGrow' || settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse') {
createBoxes(slider, settings, vars);
var totalBoxes = settings.boxCols * settings.boxRows;
var i = 0;
var timeBuff = 0;
var rowIndex = 0;
var colIndex = 0;
var box2Darr = new Array();
box2Darr[rowIndex] = new Array();
var boxes = $('.nivo-box', slider);
if (settings.effect == 'boxRainReverse' || vars.randAnim == 'boxRainReverse' || settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse') {
boxes = $('.nivo-box', slider)._reverse();
}
boxes.each(function() {
box2Darr[rowIndex][colIndex] = $(this);
colIndex++;
if (colIndex == settings.boxCols) {
rowIndex++;
colIndex = 0;
box2Darr[rowIndex] = new Array();
}
});
for (var cols = 0; cols < (settings.boxCols * 2); cols++) {
var prevCol = cols;
for (var rows = 0; rows < settings.boxRows; rows++) {
if (prevCol >= 0 && prevCol < settings.boxCols) {
(function(row, col, time, i, totalBoxes) {
var box = $(box2Darr[row][col]);
var w = box.width();
var h = box.height();
if (settings.effect == 'boxRainGrow' || vars.randAnim == 'boxRainGrow' || settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse') {
box.width(0).height(0);
}
if (i == totalBoxes - 1) {
setTimeout(function() {
box.animate({
opacity : '1',
width : w,
height : h
}, settings.animSpeed / 1.3, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + time));
} else {
setTimeout(function() {
box.animate({
opacity : '1',
width : w,
height : h
}, settings.animSpeed / 1.3);
}, (100 + time));
}
})(rows, prevCol, timeBuff, i, totalBoxes);
i++;
}
prevCol--;
}
timeBuff += 100;
}
}
}
var shuffle = function(arr) {
for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
var trace = function(msg) {
if (this.console && typeof console.log != "undefined")
console.log(msg);
}
this.stop = function() {
if (!$(element).data('nivo:vars').stop) {
$(element).data('nivo:vars').stop = true;
trace('Stop Slider');
}
}
this.start = function() {
if ($(element).data('nivo:vars').stop) {
$(element).data('nivo:vars').stop = false;
trace('Start Slider');
}
}
settings.afterLoad.call(this);
return this;
};
$.fn.nivoSlider = function(options) {
return this.each(function(key, value) {
var element = $(this);
if (element.data('nivoslider'))
return element.data('nivoslider');
var nivoslider = new NivoSlider(this, options);
element.data('nivoslider', nivoslider);
});
};
$.fn.nivoSlider.defaults = {
backgroundSize:'',
effect : 'random',
slices : 15,
boxCols : 8,
boxRows : 4,
animSpeed : 500,
pauseTime : 3000,
startSlide : 0,
directionNav : true,
directionNavHide : true,
controlNav : true,
controlNavThumbs : false,
controlNavThumbsFromRel : false,
controlNavThumbsSearch : '.jpg',
controlNavThumbsReplace : '_thumb.jpg',
keyboardNav : true,
pauseOnHover : true,
manualAdvance : false,
captionOpacity : 0.8,
prevText : 'Prev',
nextText : 'Next',
beforeChange : function() {
},
afterChange : function() {
},
slideshowEnd : function() {
},
lastSlide : function() {
},
afterLoad : function() {
}
};
$.fn._reverse = [].reverse;
})(jQuery);
When you initial nivoSlide pass my new parameter backgroundSize:'your width size px your height size px';
Example:
$('#slider').nivoSlider({
backgroundSize:'687px 400px',
effect: 'random',
animSpeed: 500,
pauseTime: 3000,
directionNav: true,
controlNav: true,
controlNavThumbs: false,
pauseOnHover: true});
});

Resources