### Basic Axis Setup Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/axis.md Sets up and renders both X and Y axes with specified scales, orientations, tick counts, and formats. ```kotlin val xScale = Scale { x -> x * 10f } val yScale = Scale { y -> 500f - y * 2f } val xAxis = axis() .scale(xScale) .orient(Orient.Bottom) .tickCount(5) val yAxis = axis() .scale(yScale) .orient(Orient.Left) .tickCount(5) .tickFormat { it.toInt().toString() } val xAxisElement = xAxis(parentGroup) val yAxisElement = yAxis(parentGroup) ``` -------------------------------- ### Kotlin Interval Example Usage Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/time.md Demonstrates creating standard intervals, flooring times to the start of an interval, generating time ranges, and counting intervals. ```kotlin import kotlinx.datetime.LocalDateTime // Create intervals val hourly = hour() val daily = day() val monthly = month() // Floor times val time = LocalDateTime(2024, 1, 15, 14, 37, 45) println(hourly.floor(time)) // 2024-01-15 14:00:00 println(daily.floor(time)) // 2024-01-15 00:00:00 println(monthly.floor(time)) // 2024-01-01 00:00:00 // Generate ranges val hours = hourly.range( LocalDateTime(2024, 1, 15, 12, 0), LocalDateTime(2024, 1, 15, 18, 0) ) // [12:00, 13:00, 14:00, 15:00, 16:00, 17:00] // Count intervals val dayCount = daily.count( LocalDateTime(2024, 1, 1, 0, 0), LocalDateTime(2024, 1, 31, 0, 0) ) // Returns 30 // Every nth interval val every2hours = hourly.every(2) val every3months = monthly.every(3) // Skip weekends val weekdays = daily().filter { it.dayOfWeek !in DayOfWeek.SATURDAY..DayOfWeek.SUNDAY } ``` -------------------------------- ### Clip.Path Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md An example demonstrating how to create a circular clip region using Clip.Path. ```kotlin val circularClip = Clip.Path(Path { moveTo(50f, 0f) arcTo(0f, 0f, 100f, 100f, 0f, 360f, true) }) ``` -------------------------------- ### Setup Pie Chart Source: https://github.com/juullabs/krayon/blob/main/sample/src/jsMain/resources/index.html Initializes a pie chart on the specified canvas element. ```kotlin sample.setupPieChart(document.getElementById("pie-canvas")) ``` -------------------------------- ### Example: Creating a Triangle Path Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Demonstrates how to create a triangle shape using the Path builder DSL. ```kotlin val triangle = Path { moveTo(0f, 0f) lineTo(100f, 0f) lineTo(50f, 100f) close() } ``` -------------------------------- ### Convert Color to Hex String Examples Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/color.md Shows examples of converting opaque and semi-transparent colors to their hex string representations. ```kotlin Color(255, 128, 64).toHexString() // Returns "#FF8040" Color(128, 255, 0, 0).toHexString() // Returns "#FF000080" ``` -------------------------------- ### Clip.Rect Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md An example demonstrating how to create a rectangular clip region. ```kotlin Clip.Rect(10f, 10f, 100f, 100f) ``` -------------------------------- ### Interpolator Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Demonstrates creating an Interpolator and calculating interpolated values at different fractions. ```kotlin val interp = interpolator(0, 100) val value25 = interp.interpolate(0.25f) // Returns 25 val value75 = interp.interpolate(0.75f) // Returns 75 ``` -------------------------------- ### Create and Configure TextElement Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/element.md Example of creating a TextElement and setting its text, position, and paint properties. ```kotlin val label = TextElement().apply { text = "Hello World" x = 50f y = 50f paint = Paint.Text( color = black, size = 14f, alignment = Paint.Text.Alignment.Center, font = Font(sansSerif) ) } ``` -------------------------------- ### Setup Interactive Chart Source: https://github.com/juullabs/krayon/blob/main/sample/src/jsMain/resources/index.html Initializes an interactive chart on the specified canvas element. ```kotlin sample.setupInteractiveChart(document.getElementById("interaction-canvas")) ``` -------------------------------- ### Clamp Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Demonstrates how to use the clamp utility to restrict an interpolated value to a maximum bound. The example uses a numeric interpolator and coerces the result. ```kotlin val interp = interpolator(10f, 90f) val value = interp.interpolate(1.5f).coerceIn(10f, 90f) // Clamps to 90f ``` -------------------------------- ### Font Creation Examples Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Demonstrates various ways to create Font objects using different constructors and predefined constants. ```kotlin Font("Helvetica", sansSerif) Font("Courier New", monospace) Font(listOf("Arial", "Verdana", sansSerif)) ``` -------------------------------- ### Line Chart Generation Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/shape.md Demonstrates how to create and use a line generator with custom data points and configuration. ```kotlin data class Point(val x: Float, val y: Float) val lineGen = line() .x { it.x } .y { it.y } .curve(Linear()) val data = listOf( Point(0f, 100f), Point(50f, 75f), Point(100f, 50f), ) val path = lineGen(data) ``` -------------------------------- ### Instant Interpolator Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Demonstrates creating and using an instant interpolator for temporal values. Shows how to interpolate to find a midpoint time. ```kotlin val start = Instant.parse("2024-01-01T00:00:00Z") val end = Instant.parse("2024-01-02T00:00:00Z") val interp = interpolator(start, end) val midpoint = interp.interpolate(0.5f) // Noon on 2024-01-01 ``` -------------------------------- ### BidirectionalInterpolator Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Demonstrates using a BidirectionalInterpolator to interpolate a value and then invert it back to a fraction. ```kotlin val interp = interpolator(10f, 90f) as BidirectionalInterpolator val value = interp.interpolate(0.5f) // Returns 50f val fraction = interp.invert(50f) // Returns 0.5f ``` -------------------------------- ### ContinuousAxis Example Usage Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/axis.md Demonstrates the creation and configuration of a ContinuousAxis with a scale, orientation, tick size, and tick count. ```kotlin data class DataPoint(val x: Int, val y: Float) val xScale = /* Scale */ val xAxis = axis() .scale(xScale) .orient(Orient.Bottom) .tickSize(6f) .tickCount(10) val axisElement = xAxis(parentGroup) ``` -------------------------------- ### Configure Pie Generator: Start Angle Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/shape.md Sets the starting angle for the first slice in degrees. Defaults to 0. ```kotlin fun startAngle(value: Float): Pie ``` -------------------------------- ### Example: Building and Traversing a Hierarchy Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/hierarchy.md Demonstrates creating a hierarchy from a data class and then iterating through it using eachBefore to print node names with indentation based on depth. ```kotlin data class Category( val name: String, val subcategories: List = emptyList(), ) val root = hierarchy(rootCategory) { it.subcategories } root.eachBefore { println("${" ".repeat(it.depth)}${it.data.name}") } ``` -------------------------------- ### Create and Configure CircleElement Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/element.md Example of creating a CircleElement instance and setting its properties like center coordinates, radius, and paint style. ```kotlin val circle = CircleElement().apply { centerX = 50f centerY = 50f radius = 25f paint = Paint.Fill(red) } ``` -------------------------------- ### Example of Splitting a Scale Transform Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Demonstrates how to use the split() function to decompose a Scale transformation into an InOrder transformation. ```kotlin val scaled = Transform.Scale(2f, 2f, 50f, 50f) // Scale 2x around (50, 50) val decomposed = scaled.split() // Now as InOrder ``` -------------------------------- ### PathBuilder moveTo() Method Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Sets the starting point for the next contour in the path. ```kotlin fun moveTo(x: Float, y: Float) ``` -------------------------------- ### Example: Flat Hierarchy with Aggregation Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/hierarchy.md Shows how to create a flat hierarchy from a list of items and then use a sum aggregation on the node values. ```kotlin val items = listOf(item1, item2, item3) val root = flatHierarchy(items) root.sum { it.value } // Compute totals ``` -------------------------------- ### Integer Interpolator Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Demonstrates creating and using an integer interpolator. Shows how to interpolate a value and invert a range value back to a fraction. ```kotlin val interp = interpolator(0, 255) val value = interp.interpolate(0.5f) // Returns 127 or 128 val fraction = interp.invert(200) // Returns ~0.784 ``` -------------------------------- ### Axis Patterns Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/axis.md Provides examples for setting up basic axes and custom ticks using the ContinuousAxis class. ```APIDOC ## Axis Patterns ### Basic Axis Setup ```kotlin val xScale = Scale { x -> x * 10f } val yScale = Scale { y -> 500f - y * 2f } val xAxis = axis() .scale(xScale) .orient(Orient.Bottom) .tickCount(5) val yAxis = axis() .scale(yScale) .orient(Orient.Left) .tickCount(5) .tickFormat { it.toInt().toString() } val xAxisElement = xAxis(parentGroup) val yAxisElement = yAxis(parentGroup) ``` ### Custom Ticks ```kotlin val axis = axis() .scale(scale) .tickValues(listOf(0f, 25f, 50f, 75f, 100f)) .tickFormat { it.toString() } ``` ``` -------------------------------- ### Setup Moving Sine Wave Chart Source: https://github.com/juullabs/krayon/blob/main/sample/src/jsMain/resources/index.html Initializes a moving sine wave line chart on the specified canvas element. ```kotlin sample.setupMovingSineWave(document.getElementById("line-canvas")) ``` -------------------------------- ### Pie Chart Slice Generation Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/shape.md Demonstrates how to create a Pie generator, configure value extraction and padding, and then generate slices from sample data. ```kotlin data class DataPoint(val label: String, val value: Float) val pieGen = pie() .value { it.value } .padAngle(2f) val data = listOf( DataPoint("A", 30f), DataPoint("B", 20f), DataPoint("C", 50f), ) val slices = pieGen(data) ``` -------------------------------- ### RectangleElement Usage Examples Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/box.md Demonstrates how to create a RectangleElement, access its bounds, and modify its dimensions and center using the extension properties. ```kotlin val rect = RectangleElement().apply { left = 10f top = 10f width = 100f height = 50f } // Access bounds println("Width: ${rect.width}") // 100f println("Height: ${rect.height}") // 50f println("Center: ${rect.centerX}, ${rect.centerY}") // 60f, 35f // Modify via computed properties rect.width = 150f // Extends right edge rect.height = 75f // Extends bottom edge // Change center rect.centerX = 200f rect.centerY = 200f ``` -------------------------------- ### Temporal Scaling Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/scale.md Shows how to map a domain of dates (LocalDateTime) to a numeric range, typically for positioning elements on a timeline. ```kotlin val timeScale: Scale = ... val xCoord = timeScale(someDate) ``` -------------------------------- ### Color Interpolator Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Demonstrates creating and using a color interpolator to find an intermediate color between two given colors. ```kotlin val interp = interpolator(red, blue) val purple = interp.interpolate(0.5f) // Midpoint between red and blue ``` -------------------------------- ### Configure and Create a RectangleElement Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/element.md Example of creating a RectangleElement and configuring its dimensions (left, top, right, bottom) and paint style (Fill with blue color). ```kotlin val rect = RectangleElement().apply { left = 10f top = 10f right = 110f bottom = 50f paint = Paint.Fill(blue) } ``` -------------------------------- ### Custom Ticks Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/axis.md Configures an axis with explicitly defined tick values and a custom tick format. ```kotlin val axis = axis() .scale(scale) .tickValues(listOf(0f, 25f, 50f, 75f, 100f)) .tickFormat { it.toString() } ``` -------------------------------- ### Path get() Method Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Converts the path to a platform-specific type using a provided marker and caches the result. ```kotlin fun get(marker: PathTypeMarker): T ``` -------------------------------- ### Swift Setup for CGContextKanvas Source: https://github.com/juullabs/krayon/blob/main/kanvas/README.md Initialize a CGContextKanvas in Swift for drawing with Core Graphics primitives. Handles scaling and color space configuration. ```swift // Define some constants. Here `scale` is used to handle retina 2x scaling let width = 400 let height = 300 let scale = 2 // Create a context and pass it to Krayon var cgContext: CGContext = CGContext( data: nil, width: width * scale, height: height * scale, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue )! cgContext.scaleBy(x: scale, y: scale) // Note that Kanvas uses the unscaled size, which does not match the pixel count of the CGContext let kanvas = CGContextKanvas(ptr: &cgContext, width: width, height: height) ``` -------------------------------- ### PathBuilder relativeMoveTo() Method Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Moves the current point relative to its current position to start the next contour. ```kotlin fun relativeMoveTo(x: Float, y: Float) ``` -------------------------------- ### Create Arc Path with Custom Padding and Rounding Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/shape.md Example demonstrating the creation of an arc path with custom corner rounding and padding radius calculation. ```kotlin val arcGen = arc(100f, 50f) .cornerRadius(5f) .padRadius { _, _, _, pad -> 2f } val path = arcGen(0f, 180f, 5f) ``` -------------------------------- ### Apply Scale Transformation with TransformElement Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/element.md Example of creating a TransformElement and applying a scale transformation to it, then appending a child element. ```kotlin val scaled = TransformElement().apply { transform = Transform.Scale(2f, 2f) appendChild(originalElement) } ``` -------------------------------- ### Numeric Scaling Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/scale.md Illustrates mapping a numeric data range to a pixel range, a common use case for visual representation. ```kotlin // Example: Map data range 0-100 to pixel range 0-500 val xScale: Scale = ... val pixelX = xScale(dataValue) ``` -------------------------------- ### Example: Generating and Using Treemap Layout Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/hierarchy.md Demonstrates creating a treemap layout, configuring its dimensions and padding, and then applying it to hierarchical data. It shows how to access the computed rectangle for each node. ```kotlin data class Item(val label: String, val value: Float) val data = hierarchy(rootItem) { it.children } .sum { it.value } val layout = treemap() .width(800f) .height(600f) .padding(4f) .tile(Squarify()) val withLayout = layout(data) withLayout.each { val rect = it.layout println("${it.data.label}: ${rect.x}, ${rect.y}, ${rect.width}, ${rect.height}") } ``` -------------------------------- ### Copy Color Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/color.md Demonstrates creating a semi-transparent red color by copying an existing red color and modifying its alpha component. ```kotlin val red = Color(255, 0, 0) val darkRed = red.copy(alpha = 128) // Semi-transparent red ``` -------------------------------- ### Categorical Scaling Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/scale.md Demonstrates mapping string categories to a range of colors, useful for assigning distinct colors to different data categories. ```kotlin val colorScale: Scale = ... val color = colorScale("category_a") ``` -------------------------------- ### Generate Path for Angles Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/shape.md Generates a Path for specified start angle, end angle, and padding angle. ```kotlin operator fun invoke( startAngle: Float, endAngle: Float, padAngle: Float, ): Path ``` -------------------------------- ### Gradle Setup for Platform-Specific Dependencies Source: https://github.com/juullabs/krayon/blob/main/kanvas/README.md Add platform-specific Kanvas dependencies in Gradle. Replace `$platform` with the target platform identifier. ```kotlin repositories { mavenCentral() } dependencies { implementation("com.juul.krayon:kanvas-$platform:$version") } ``` -------------------------------- ### Kotlin Interval Counting Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/time.md Demonstrates how to use the 'every()' method to create a custom interval and then count the occurrences within a specified date range. ```kotlin val every2hours = hourly().every(2) ``` -------------------------------- ### Create Donut Arc Generator Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/shape.md Example of creating a donut shape generator using the arc factory function. ```kotlin val arcGen = arc(100f, 50f) // Donut shape ``` -------------------------------- ### Create a PathElement with a Triangle Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/element.md Example of creating a PathElement and defining a triangular path. Sets the paint to a solid fill with green color. ```kotlin val triangle = PathElement().apply { path = Path { moveTo(0f, 100f) lineTo(50f, 0f) lineTo(100f, 100f) close() } paint = Paint.Fill(green) } ``` -------------------------------- ### Kotlin Interval Counting Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/time.md Demonstrates counting the number of daily intervals between two specific dates. The result is the number of full days within the range. ```kotlin val days = daily() val count = days.count( LocalDateTime(2024, 1, 1, 0, 0), LocalDateTime(2024, 1, 15, 0, 0) ) // Returns 14 ``` -------------------------------- ### Scale invoke() Operator Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/scale.md Demonstrates how to use the invoke operator to scale a value. This is equivalent to calling the scale() method directly. ```kotlin val scale: Scale = ... val mapped = scale(100) // Equivalent to scale.scale(100) ``` -------------------------------- ### Build and Use a GroupElement Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/element.md Example of building a GroupElement, appending child elements (rectangle and circle), and drawing it on a canvas. The canvas will render all appended children. ```kotlin val group = GroupElement.build() group.appendChild(rectangle) group.appendChild(circle) kanvas.drawGroup(group) // Draws both children ``` -------------------------------- ### Gradle Setup for Multiplatform Source: https://github.com/juullabs/krayon/blob/main/kanvas/README.md Configure Kanvas dependency for multiplatform projects using Gradle Kotlin DSL. Ensure repositories and target platforms are set up correctly. ```kotlin plugins { id("com.android.application") // or id("com.android.library") kotlin("multiplatform") } repositories { mavenCentral() } kotlin { androidTarget() jvm() sourceSets { val commonMain by getting { dependencies { implementation("com.juul.krayon:kanvas:$version") } } } } android { // ... } ``` -------------------------------- ### Builder Pattern Example Source: https://github.com/juullabs/krayon/blob/main/_autodocs/00-START-HERE.md Demonstrates method chaining using the builder pattern for configuring an arc. Configuration methods return 'this' to enable chaining. ```kotlin arc(100f, 50f) .cornerRadius(5f) .padRadius { _, _, _, p -> sqrt(p) } ``` -------------------------------- ### Creating a Line with Linear Curve Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/shape.md Example of creating a line generator using the Linear curve implementation. Requires DataPoint type with x and y properties. ```kotlin val line = line() .x { it.x } .y { it.y } .curve(Linear()) val path = line(data) ``` -------------------------------- ### CocoaPods Plugin Setup for Apple Targets Source: https://github.com/juullabs/krayon/blob/main/kanvas/README.md Configure the cocoapods plugin in your Kotlin module for Apple targets. Ensure Krayon modules are exported for Swift/Objective-C usage. ```kotlin plugins { kotlin("multiplatform") kotlin("native.cocoapods") } // ... cocoapods { // ... framework { // ... export("com.juul.krayon:$module:$version") } } ``` -------------------------------- ### Interval.Count.count() Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/time.md Counts the number of intervals between a specified start and stop time. ```APIDOC ## count() ### Description Count intervals between two times. ### Method ```kotlin fun count(start: LocalDateTime, stop: LocalDateTime): Int ``` ### Parameters #### Path Parameters - **start** (LocalDateTime) - Required - Start time - **stop** (LocalDateTime) - Required - Stop time ### Returns Number of intervals ### Example ```kotlin val days = daily() val count = days.count( LocalDateTime(2024, 1, 1, 0, 0), LocalDateTime(2024, 1, 15, 0, 0) ) // Returns 14 ``` ``` -------------------------------- ### Offset Time by Interval Steps Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/time.md Adds or subtracts a specified number of intervals from a starting time. Useful for calculating future or past dates/times relative to a reference point. ```kotlin val dayInterval = daily() val time = LocalDateTime(2024, 1, 15, 10, 30) val nextDay = dayInterval.offset(time, 1) // Next day val twoWeeks = dayInterval.offset(time, 14) // Two weeks later ``` -------------------------------- ### Build and Draw Path Source: https://github.com/juullabs/krayon/blob/main/_autodocs/README.md Shows how to construct a path using moveTo, lineTo, and close commands, then draw it on a Kanvas with a fill paint. Ensure the PathBuilder is correctly initialized. ```kotlin val path = Path { moveTo(0f, 0f) lineTo(100f, 0f) lineTo(50f, 100f) close() } kanvas.drawPath(path, Paint.Fill(green)) ``` -------------------------------- ### PathBuilder reset() Method Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Clears the path, effectively starting a new path construction. ```kotlin fun reset() ``` -------------------------------- ### Apply Clip Region to ClipElement Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/element.md Example of how to set the clip region for a ClipElement and append child elements. Children will only be visible within the defined rectangular clip area. ```kotlin val clipped = ClipElement().apply { clip = Clip.Rect(0f, 0f, 100f, 100f) appendChild(largeElement) // Visible only within rectangle } ``` -------------------------------- ### Interpolate Method Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Calculates the interpolated value at a specific fraction between the start and stop values. ```kotlin fun interpolate(fraction: Float): T ``` -------------------------------- ### Node Breadth-First Traversal Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/hierarchy.md Performs a breadth-first traversal of the tree starting from the current node. ```kotlin fun Node.traverseBreadthFirst(): Sequence> ``` -------------------------------- ### LineElement Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/element.md Represents a drawable line segment. It allows customization of its start and end points, and how it is painted. ```APIDOC ## LineElement ### Description Drawable line segment. Allows customization of start and end coordinates, and paint properties. ### Properties - **startX** (Float) - 0f - Start x-coordinate - **startY** (Float) - 0f - Start y-coordinate - **endX** (Float) - 0f - End x-coordinate - **endY** (Float) - 0f - End y-coordinate - **paint** (Paint) - DEFAULT_STROKE - How to paint the line - **tag** (String) - "line" - Element type ``` -------------------------------- ### Interpolator Interface Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Generates interpolated values between a start and stop value at a given fraction (0.0-1.0). ```APIDOC ## Interpolator Interface ### Description Generates interpolated values between a start and stop value at a given fraction (0.0-1.0). ### Type Parameters * **T** - Value type being interpolated ### Methods #### interpolate() ```kotlin fun interpolate(fraction: Float): T ``` Calculate the interpolated value at a given point between start and stop. #### Parameters * **fraction** (Float) - Required - Interpolation factor (0.0 = start, 1.0 = stop) #### Returns Interpolated value #### Example ```kotlin val interp = interpolator(0, 100) val value25 = interp.interpolate(0.25f) // Returns 25 val value75 = interp.interpolate(0.75f) // Returns 75 ``` ``` -------------------------------- ### Using Web Color Constants Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/color.md Demonstrates how to use predefined color constants for fill, stroke, and background colors. Includes importing colors and modifying alpha values. ```kotlin import com.juul.krayon.color.* val fillColor = red val strokeColor = navy.copy(alpha = 200) val background = lightGray ``` -------------------------------- ### Paint.Gradient.Linear Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Defines a linear gradient that transitions between colors along a line defined by start and end points. ```APIDOC ## Paint.Gradient.Linear ### Description Linear gradient from start point to end point. ### Properties #### startX (Float) - Required #### startY (Float) - Required #### endX (Float) - Required #### endY (Float) - Required #### stops (List) - Required ### Example ```kotlin Paint.Gradient.Linear( 0f, 0f, 100f, 100f, Paint.Gradient.Stop(0f, red), Paint.Gradient.Stop(1f, blue) ) ``` ``` -------------------------------- ### interpolator(Double, Double) Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Creates a bidirectional interpolator for linear double interpolation between a start and stop double value. ```APIDOC ## interpolator(Double, Double) Linear double interpolation. | Parameter | |-----------| | start (Double) - Starting double | | stop (Double) - Ending double | **Returns:** Bidirectional interpolator ``` -------------------------------- ### interpolator(Float, Float) Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Creates a bidirectional interpolator for linear float interpolation between a start and stop float value. ```APIDOC ## interpolator(Float, Float) Linear float interpolation. | Parameter | |-----------| | start (Float) - Starting float | | stop (Float) - Ending float | **Returns:** Bidirectional interpolator ``` -------------------------------- ### interpolator(Int, Int) Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Creates a bidirectional interpolator for linear integer interpolation between a start and stop integer value. ```APIDOC ## interpolator(Int, Int) Linear integer interpolation. | Parameter | |-----------| | start (Int) - Starting integer | | stop (Int) - Ending integer | **Returns:** Bidirectional interpolator **Example:** ```kotlin val interp = interpolator(0, 255) val value = interp.interpolate(0.5f) // Returns 127 or 128 val fraction = interp.invert(200) // Returns ~0.784 ``` ``` -------------------------------- ### Cache Interface Definition Source: https://github.com/juullabs/krayon/blob/main/_autodocs/types.md Defines a generic interface for a cache with key-value operations, including get, set, and getOrPut. ```kotlin interface Cache { operator fun get(key: K): V? operator fun set(key: K, value: V) fun getOrPut(key: K, defaultValue: () -> V): V } ``` -------------------------------- ### RectangleElement Extensions Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/box.md Provides extension properties for RectangleElement to easily get or set its bounds, dimensions, and center coordinates. ```APIDOC ## RectangleElement Extensions ### Extension Properties #### top Get or set the top edge y-coordinate. ```kotlin var RectangleElement.top: Float ``` #### left Get or set the left edge x-coordinate. ```kotlin var RectangleElement.left: Float ``` #### bottom Get or set the bottom edge y-coordinate. ```kotlin var RectangleElement.bottom: Float ``` #### right Get or set the right edge x-coordinate. ```kotlin var RectangleElement.right: Float ``` #### width Get or set width (computed as right - left). ```kotlin var RectangleElement.width: Float ``` #### height Get or set height (computed as bottom - top). ```kotlin var RectangleElement.height: Float ``` #### centerX Get or set center X coordinate (computed as (left + right) / 2). ```kotlin var RectangleElement.centerX: Float ``` #### centerY Get or set center Y coordinate (computed as (top + bottom) / 2). ```kotlin var RectangleElement.centerY: Float ``` ### Usage Examples ```kotlin val rect = RectangleElement().apply { left = 10f top = 10f width = 100f height = 50f } // Access bounds println("Width: ${rect.width}") // 100f println("Height: ${rect.height}") // 50f println("Center: ${rect.centerX}, ${rect.centerY}") // 60f, 35f // Modify via computed properties rect.width = 150f // Extends right edge rect.height = 75f // Extends bottom edge // Change center rect.centerX = 200f rect.centerY = 200f ``` ``` -------------------------------- ### Create Scene Graph with Elements Source: https://github.com/juullabs/krayon/blob/main/_autodocs/README.md Illustrates building a scene graph using GroupElement and appending child elements like RectangleElement and CircleElement. Each element can have its own paint and layout properties. ```kotlin val root = GroupElement().apply { appendChild(RectangleElement().apply { left = 10f; top = 10f; right = 110f; bottom = 60f paint = Paint.Fill(red) }) appendChild(CircleElement().apply { centerX = 150f; centerY = 75f; radius = 25f paint = Paint.Fill(blue) }) } root.draw(kanvas) ``` -------------------------------- ### Creating an Arc Generator Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/shape.md Demonstrates creating an arc generator with specified dimensions and corner radius. Angles are in degrees. ```kotlin val arcGen = arc(100f, 50f) .cornerRadius(5f) val path1 = arcGen(0f, 180f, 0f) // 180° arc from right to left val path2 = arcGen(90f, 270f, 5f) // 180° arc from bottom to top, 5° padding ``` -------------------------------- ### PathBuilder close() Method Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Closes the current contour by drawing a straight line from the current point to the starting point of the contour. ```kotlin fun close() ``` -------------------------------- ### Create or Update Elements with Krayon Selection Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/selection.md Shows how to select parent elements, bind data, and then append new elements for entering data while removing exiting elements. ```kotlin val selection = parent.selectAll(RectangleElement) val update = selection.data(data) { it.id } update.enter.append(RectangleElement) update.attr("y", Point.y) update.exit.remove() ``` -------------------------------- ### Utility Modules Source: https://github.com/juullabs/krayon/blob/main/_autodocs/modules.md Integrate utility modules for scaling, value interpolation, time manipulation, and box utilities. ```kotlin implementation("com.juul.krayon:scale:1.0.0") implementation("com.juul.krayon:interpolate:1.0.0") implementation("com.juul.krayon:time:1.0.0") implementation("com.juul.krayon:box:1.0.0") ``` -------------------------------- ### Drawing a Rectangle with Krayon Source: https://github.com/juullabs/krayon/blob/main/_autodocs/INDEX.md Demonstrates how to draw a rectangle on a canvas using the Kanvas interface and Paint.Fill. ```kotlin val paint = Paint.Fill(red) kanvas.drawRect(10f, 10f, 100f, 50f, paint) ``` -------------------------------- ### UpdateSelection Typical Usage Pattern Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/selection.md Demonstrates a typical usage pattern for the UpdateSelection class, showing how to bind data, append new elements, remove old elements, and set attributes. ```kotlin val update = elements.data(newData, { it.id }) update.enter.append(RectangleElement)... update.exit.remove() update.attr("x") { _, _, i -> i * 10f } ``` -------------------------------- ### Configure Multiplatform Gradle Project Source: https://github.com/juullabs/krayon/blob/main/color/README.md Add the Krayon color dependency to your common main source set for multiplatform projects. Ensure you have the necessary Android and Kotlin plugins applied. ```kotlin plugins { id("com.android.application") // or id("com.android.library") kotlin("multiplatform") } repositories { mavenCentral() } kotlin { androidTarget() jvm() sourceSets { val commonMain by getting { dependencies { implementation("com.juul.krayon:color:$version") } } } } android { // ... } ``` -------------------------------- ### Define Interpolator Interface Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Defines the basic Interpolator interface for generating interpolated values between a start and stop point based on a fraction. ```kotlin interface Interpolator ``` -------------------------------- ### Hypothetical LinearScale Implementation and Usage Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/scale.md Presents a hypothetical implementation of a LinearScale and its usage pattern, demonstrating how to map a continuous numeric domain to a continuous numeric range. ```kotlin // Hypothetical implementation pattern class LinearScale(val domainMin: Float, val domainMax: Float, val rangeMin: Float, val rangeMax: Float) : Scale { override fun scale(input: Float): Float { return rangeMin + (input - domainMin) / (domainMax - domainMin) * (rangeMax - rangeMin) } } // Usage val scale = LinearScale(0f, 100f, 0f, 500f) val pixelPosition = scale(50f) // Returns 250f ``` -------------------------------- ### Kotlin count() Method for Interval Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/time.md Counts the number of intervals between a specified start and stop LocalDateTime. Requires an Interval implementation to be defined. ```kotlin fun count(start: LocalDateTime, stop: LocalDateTime): Int ``` -------------------------------- ### Implement Squarify TileMethod Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/hierarchy.md Implements the Squarify algorithm for partitioning rectangles, aiming for squarish shapes to improve readability. The target aspect ratio can be configured. ```kotlin class Squarify(val ratio: Float = 1.6f) : TileMethod() ``` -------------------------------- ### Handling Nested Groups with Krayon Selection Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/selection.md Illustrates how to create nested groups and then bind data to rectangles within each group, managing enter and update selections for both levels. ```kotlin val groupSelection = svg.selectAll(GroupElement) .data(groupData) { it.id } groupSelection.enter.append(GroupElement) .attr("transform") { d, _, _ -> Transform.Translate(d.x, d.y) } groupSelection.each { groupElement, groupData, _ -> groupElement.selectAll(RectangleElement) .data(groupData.items) { it.id } .enter.append(RectangleElement) } ``` -------------------------------- ### Create Pie Generator Function Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/shape.md Initializes a new Pie generator instance. This is the entry point for configuring pie chart generation. ```kotlin fun pie(): Pie ``` -------------------------------- ### Color Constructors Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/color.md Provides details on various ways to construct a Color object, from ARGB integers, component integers, or component floats. ```APIDOC ## Color(Int) ### Description Create a color directly from an ARGB integer. ### Parameters #### Path Parameters - **argb** (Int) - Yes - 32-bit ARGB value ## Color(Int, Int, Int, Int) ### Description Create a color from component integers. Each component is masked to its last eight bits (0-255). ### Parameters #### Path Parameters - **alpha** (Int) - Yes - Alpha channel (0-255) - **red** (Int) - Yes - Red channel (0-255) - **green** (Int) - Yes - Green channel (0-255) - **blue** (Int) - Yes - Blue channel (0-255) ## Color(Int, Int, Int) ### Description Create an opaque color (alpha = 255) from component integers. ### Parameters #### Path Parameters - **red** (Int) - Yes - Red channel (0-255) - **green** (Int) - Yes - Green channel (0-255) - **blue** (Int) - Yes - Blue channel (0-255) ## Color(Float, Float, Float, Float) ### Description Create a color from component floats. Each component is multiplied by 255 and rounded. ### Parameters #### Path Parameters - **alpha** (Float) - Yes - Alpha channel (0.0-1.0) - **red** (Float) - Yes - Red channel (0.0-1.0) - **green** (Float) - Yes - Green channel (0.0-1.0) - **blue** (Float) - Yes - Blue channel (0.0-1.0) ## Color(Float, Float, Float) ### Description Create an opaque color from component floats. ### Parameters #### Path Parameters - **red** (Float) - Yes - Red channel (0.0-1.0) - **green** (Float) - Yes - Green channel (0.0-1.0) - **blue** (Float) - Yes - Blue channel (0.0-1.0) ``` -------------------------------- ### Implement SliceAndDice TileMethod Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/hierarchy.md Implements the SliceAndDice algorithm, a simpler recursive partitioning method that results in less balanced rectangles compared to Squarify. ```kotlin object SliceAndDice : TileMethod() ``` -------------------------------- ### Krayon Selection API Update Cycle Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/selection.md Demonstrates the three-part update cycle: binding data, handling new elements (enter), removing old elements (exit), and updating existing elements. ```kotlin val data = listOf(10, 20, 30, 40) // 1. Bind data to selection val update = elements.data(data) { it } // 2. Handle new data (enter selection) update.enter .append(RectangleElement) .attr("width") { d, _, _ -> d * 10f } // 3. Handle removed data (exit selection) update.exit.remove() // 4. Update all elements update.attr("x") { _, _, i -> i * 50f } ``` -------------------------------- ### Draw Arc on Kanvas Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Draws an arc inscribed in a specified rectangle. Requires defining the bounding box, start and sweep angles, and the paint style. ```kotlin fun drawArc( left: Float, top: Float, right: Float, bottom: Float, startAngle: Float, sweepAngle: Float, paint: Paint, ) ``` ```kotlin kanvas.drawArc(0f, 0f, 100f, 100f, 0f, 180f, Paint.Fill(red)) ``` -------------------------------- ### Color Constructor from ARGB Integer Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/color.md Creates a Color instance directly from a 32-bit ARGB integer. ```kotlin constructor(argb: Int) ``` -------------------------------- ### Node EachBefore Iteration Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/hierarchy.md Executes an action on each node in pre-order traversal. Returns the node for chaining. ```kotlin inline fun Node.eachBefore( crossinline action: (Node) -> Unit, ): Node ``` -------------------------------- ### Core Krayon Modules Source: https://github.com/juullabs/krayon/blob/main/_autodocs/modules.md Add core Krayon modules to your project for fundamental drawing and element manipulation capabilities. ```kotlin implementation("com.juul.krayon:color:1.0.0") implementation("com.juul.krayon:kanvas:1.0.0") implementation("com.juul.krayon:element:1.0.0") ``` -------------------------------- ### Numeric Linear Interpolation Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/interpolate.md Illustrates linear interpolation for numeric values. This snippet shows how to create a numeric interpolator and iterate through fractions to get interpolated values. ```kotlin // Numeric interpolation val numInterp = interpolator(0, 100) for (i in 0..10) { val fraction = i / 10f println(numInterp.interpolate(fraction)) // 0, 10, 20, ..., 100 } ``` -------------------------------- ### copy() Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/color.md Creates a copy of the current Color instance, with the option to modify specific color components. ```APIDOC ## copy() ### Description Create a copy of this color with optionally modified components. ### Parameters #### Path Parameters - **alpha** (Int) - Optional - Default: this.alpha - New alpha value - **red** (Int) - Optional - Default: this.red - New red value - **green** (Int) - Optional - Default: this.green - New green value - **blue** (Int) - Optional - Default: this.blue - New blue value ### Returns A new Color instance ### Example ```kotlin val red = Color(255, 0, 0) val darkRed = red.copy(alpha = 128) // Semi-transparent red ``` ``` -------------------------------- ### drawArc Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Draws an arc inscribed in a specified rectangle. The arc is defined by its bounding box, start angle, and sweep angle, along with a Paint object to define its appearance. ```APIDOC ## drawArc ### Description Draws an arc inscribed in the specified rectangle. ### Method `fun drawArc( left: Float, top: Float, right: Float, bottom: Float, startAngle: Float, sweepAngle: Float, paint: Paint, )` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **left** (Float) - Required - Left bound of bounding rectangle - **top** (Float) - Required - Top bound of bounding rectangle - **right** (Float) - Required - Right bound of bounding rectangle - **bottom** (Float) - Required - Bottom bound of bounding rectangle - **startAngle** (Float) - Required - Starting angle in degrees (0° is right) - **sweepAngle** (Float) - Required - Sweep angle in degrees (positive is clockwise) - **paint** (Paint) - Required - How to paint the arc ### Request Example ```kotlin kanvas.drawArc(0f, 0f, 100f, 100f, 0f, 180f, Paint.Fill(red)) ``` ### Response None ``` -------------------------------- ### Color Constructor from RGB Components (Opaque) Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/color.md Creates an opaque Color instance (alpha = 255) from red, green, and blue component integers. ```kotlin constructor(red: Int, green: Int, blue: Int) ``` -------------------------------- ### Floor Time to Interval Boundary Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/time.md Rounds a given LocalDateTime down to the nearest interval boundary. Use this when you need to find the start of the interval containing a specific point in time. ```kotlin val hourInterval = hourly() val time = LocalDateTime(2024, 1, 15, 14, 37, 45) val floored = hourInterval.floor(time) // Returns 14:00:00 ``` -------------------------------- ### Standard Interval Implementations Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/time.md Provides factory functions for common time intervals like minute, hour, day, week, month, and year. ```APIDOC ## Standard Interval Implementations ### minute() ```kotlin fun minute(): Interval.Count & Interval.Field ``` Intervals of 1 minute. ### hour() ```kotlin fun hour(): Interval.Count & Interval.Field ``` Intervals of 1 hour. ### day() ```kotlin fun day(): Interval.Count & Interval.Field ``` Intervals of 1 day (midnight to midnight). ### week() ```kotlin fun week(): Interval.Count & Interval.Field ``` Intervals of 1 week (Monday to Monday). ### month() ```kotlin fun month(): Interval.Count & Interval.Field ``` Intervals of 1 month (day 1 to day 1). ### year() ```kotlin fun year(): Interval.Count & Interval.Field ``` Intervals of 1 year (January 1 to January 1). ``` -------------------------------- ### PathBuilder quadraticTo() Method Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/kanvas.md Adds a quadratic Bézier curve segment to the path. ```kotlin fun quadraticTo( controlX: Float, controlY: Float, endX: Float, endY: Float, ) ``` -------------------------------- ### Get Interaction Path for InteractableElement Source: https://github.com/juullabs/krayon/blob/main/_autodocs/api-reference/element.md Abstract method to retrieve the path used for interaction detection, like hit testing. Implementations should return a Path object defining the interactive area. ```kotlin abstract fun getInteractionPath(): Path ``` -------------------------------- ### Common Krayon Imports Source: https://github.com/juullabs/krayon/blob/main/_autodocs/INDEX.md Import necessary classes for colors, drawing operations, elements, shapes, hierarchy, and utilities in Krayon. This covers a wide range of functionalities for graphics and data visualization. ```kotlin import com.juul.krayon.color.Color import com.juul.krayon.color.* // All named colors // Drawing import com.juul.krayon.kanvas.* // Kanvas, Paint, Path, Transform, Clip, Font // Elements import com.juul.krayon.element.* // Element, all element types // Shapes import com.juul.krayon.shape.* // Arc, Pie, Line, Slice, Curve // Hierarchy & Layout import com.juul.krayon.hierarchy.* // Node, hierarchy functions, Treemap // Utilities import com.juul.krayon.scale.Scale import com.juul.krayon.interpolate.* // Interpolator, interpolator functions import com.juul.krayon.time.* // Interval, standard intervals import com.juul.krayon.selection.* // Selection, UpdateSelection, etc. import com.juul.krayon.axis.* // ContinuousAxis, Edge import com.juul.krayon.box.* // Rectangle extensions ```