本文整理汇总了Scala中java.awt.Color类的典型用法代码示例。如果您正苦于以下问题:Scala Color类的具体用法?Scala Color怎么用?Scala Color使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Color类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: GraphicMatrix
//设置package包名称以及导入依赖的类
package swayvil.langtonant.gui
import java.awt.{ Graphics2D, BasicStroke }
import java.awt.geom._ // Rectangle2D
import swayvil.langtonant.Matrix
import swayvil.langtonant.Square
import scala.swing.Panel
import java.awt.Color
import java.awt.Dimension
class GraphicMatrix(private var m: Matrix) extends Panel with GUI {
preferredSize = new Dimension(m.size * squareSize, m.size * squareSize)
override def paintComponent(g: Graphics2D) {
m.matrix.foreach { (row: Array[Square]) => row.foreach { (square: Square) => drawSquare(g, square.x, square.y) } }
}
override def repaint() {
super.repaint()
}
private def drawSquare(g: Graphics2D, x: Int, y: Int) {
var rec = new Rectangle2D.Double(squareSize * x, squareSize * y, squareSize, squareSize)
if (m.matrix(x)(y).isWhite)
g.setColor(white)
else
g.setColor(black)
if (m.matrix(x)(y).isAnt)
g.setColor(red)
g.fill(new Rectangle2D.Double(squareSize * x, squareSize * y, squareSize, squareSize))
g.setColor(black)
g.draw(new Rectangle2D.Double(squareSize * x, squareSize * y, squareSize, squareSize))
}
}
开发者ID:swayvil,项目名称:langton-ant,代码行数:35,代码来源:GraphicMatrix.scala
示例2: Bubble
//设置package包名称以及导入依赖的类
package com.alvinalexander.bubbles
import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import java.awt.GraphicsConfiguration
import java.awt.Transparency
case class Bubble (
var x: Int,
var y: Int,
var lastX: Int,
var lastY: Int,
circleDiameter: Int,
fgColor: Color,
bgColor: Color,
char: Char
)
{
private var image: BufferedImage = null
def drawBubbleFast(g: Graphics, gc: GraphicsConfiguration) {
val g2 = g.asInstanceOf[Graphics2D]
if (image == null) {
println("image was null")
// build the image on the first call
image = gc.createCompatibleImage(circleDiameter+1, circleDiameter+1, Transparency.BITMASK)
val gImg = image.getGraphics.asInstanceOf[Graphics2D]
renderBubble(gImg)
gImg.dispose
}
g2.drawImage(image, x, y, null)
}
// given a Graphics object, render the bubble
def renderBubble(g: Graphics) {
val g2 = g.create.asInstanceOf[Graphics2D]
// draw the circle
g2.setColor(bgColor)
g2.fillOval(0, 0, circleDiameter, circleDiameter)
// draw the character
g2.setFont(CIRCLE_FONT)
g2.setColor(fgColor)
g2.drawString(char.toString, CIRCLE_FONT_PADDING_X, CIRCLE_FONT_PADDING_Y)
g2.dispose
}
}
开发者ID:arunhprasadbh,项目名称:AkkaKillTheCharactersGame,代码行数:52,代码来源:Bubble.scala
示例3: GameOver
//设置package包名称以及导入依赖的类
package com.alvinalexander
import java.awt.Color
import java.awt.Font
package object bubbles {
val SCREEN_HEIGHT = 600
val SCREEN_WIDTH = 800
val NUM_CIRCLES = 10
val CIRCLE_DIAMETER = 40
val SPACE_BETWEEN_CIRCLES = 72
val INITIAL_SPACE = 40
val CIRCLE_FONT = new Font("Sans Serif", Font.BOLD, 22)
val CIRCLE_FONT_PADDING_X = 13
val CIRCLE_FONT_PADDING_Y = 28
val APPLICATION_NAME = "Akka Actors 'Kill The Characters' Game"
val ACTOR_SYSTEM_NAME = "TinyBubbles"
val BUBBLE_PANEL_ACTOR_NAME = "bubblePanelActor"
val MAIN_FRAME_ACTOR_NAME = "mainFrameActor"
val KEY_LISTENER_ACTOR_NAME = "keyListenerActor"
val PLAY_SOUND_ACTOR_NAME = "playSoundActor"
val ACTOR_MANAGER_NAME = "actorManager"
val COLORS = Array(
(Color.WHITE, Color.BLUE),
(Color.BLACK, Color.CYAN),
(Color.BLACK, Color.GREEN),
(Color.BLACK, Color.LIGHT_GRAY),
(Color.WHITE, Color.MAGENTA),
(Color.WHITE, Color.ORANGE),
(Color.WHITE, Color.PINK),
(Color.WHITE, Color.RED),
(Color.BLACK, Color.WHITE),
(Color.BLACK, Color.YELLOW))
// actor messages
case object GameOver
}
开发者ID:arunhprasadbh,项目名称:AkkaKillTheCharactersGame,代码行数:43,代码来源:package.scala
示例4: ColorApp
//设置package包名称以及导入依赖的类
package com.esri
import java.awt.Color
import breeze.linalg.DenseVector
object ColorApp extends App {
val rnd = new java.security.SecureRandom()
val colorSeq = for (_ <- 0 until 200)
yield {
val r = rnd.nextInt(255)
val g = rnd.nextInt(255)
val b = rnd.nextInt(255)
val hsb = Color.RGBtoHSB(r, g, b, null).map(_.toDouble)
DenseVector[Double](hsb)
}
val colorLen = colorSeq.length
val somSize = 8
val nodes = for {
q <- 0 until somSize
r <- 0 until somSize
} yield Node(q, r, colorSeq(rnd.nextInt(colorLen)))
val epochMax = colorLen * 100
implicit val pb = TerminalProgressBar(epochMax)
val som = SOM(nodes)
som.train(colorSeq, epochMax, somSize / 2, initialAlpha = 0.3)
som.saveAsPNG("/tmp/som.png", 20)
}
开发者ID:mraad,项目名称:spark-som-path,代码行数:34,代码来源:ColorApp.scala
示例5: ButtonRenderer
//设置package包名称以及导入依赖的类
package ui.proofView
import java.awt.{Color, Component}
import javax.swing.{UIManager, JTable, JButton}
import javax.swing.table.TableCellRenderer
class ButtonRenderer extends JButton with TableCellRenderer {
override def getTableCellRendererComponent(table: JTable, value: Object, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component = {
if (isSelected) {
setForeground(Color.blue)
setBackground(table.getSelectionBackground())
} else {
setForeground(table.getForeground())
setBackground(UIManager.getColor("Button.background"))
}
if (value != null) {
setText(value.toString)
} else {
setText("")
}
return this
}
}
开发者ID:mariohd,项目名称:LogicCompiler,代码行数:24,代码来源:ButtonRenderer.scala
示例6: extractBinary
//设置package包名称以及导入依赖的类
package neuroflow.application.processor
import java.awt.Color
import java.io.File
import javax.imageio.ImageIO
import scala.io.Source
def extractBinary(path: String, selector: Int => Boolean): Vector[Double] = extractBinary(new File(path), selector)
def extractBinary(file: File, selector: Int => Boolean): Vector[Double] = {
val img = ImageIO.read(file)
(0 until img.getHeight).flatMap { h =>
(0 until img.getWidth).flatMap { w =>
val c = new Color(img.getRGB(w, h))
(if (selector(c.getRed) || selector(c.getBlue) || selector(c.getGreen)) 1.0 else 0.0) :: Nil
}
}
}.toVector
}
开发者ID:zenecture,项目名称:neuroflow,代码行数:22,代码来源:Image.scala
示例7: Scatter3D
//设置package包名称以及导入依赖的类
import java.awt.Color
import javax.swing.{JFrame, JPanel, WindowConstants}
import org.math.plot._
object Scatter3D {
def loadDataFromCSV(csvPath: String): JPanel = {
val data = scala.io.Source.fromFile(csvPath).getLines().map(_.split(",").map(_.trim.toDouble).toSeq)
val (x, y, z) = (data map {
case Seq(x_, y_, z_) => (x_, y_, z_)
}).toArray.unzip3
val colors = z map (x => new Color(Color.HSBtoRGB(x.toFloat, 1.0f, 0.5f)))
val plot = new Plot3DPanel()
plot.addScatterPlot("Fractal in 3D", colors, x, y, z)
plot
}
def main(args: Array[String]): Unit = {
val plot = loadDataFromCSV(args.headOption.getOrElse("D:/Programming/Projects/FractalGenerator/output.csv"))
val frame = new JFrame("Fractal3D")
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
frame.setSize(900, 900)
frame.setContentPane(plot)
frame.setVisible(true)
}
}
开发者ID:tamchow,项目名称:ScalaStuff,代码行数:27,代码来源:Scatter3D.scala
示例8: log
//设置package包名称以及导入依赖的类
package de.sciss.imperfect
import java.awt.Color
import java.awt.image.BufferedImage
import java.text.SimpleDateFormat
import java.util.{Date, Locale}
import scala.annotation.elidable
import scala.annotation.elidable.CONFIG
package object hough {
var showLog = true
private[this] val logHeader = new SimpleDateFormat("[d MMM yyyy, HH:mm''ss.SSS] 'imperfect' - ", Locale.US)
final val NominalWidth = 1920
final val NominalHeight = 1080
final val VisibleWidth = 3840
final val VisibleHeight = 540
// final val OffScreenImg = new BufferedImage(VisibleWidth, VisibleHeight, BufferedImage.TYPE_BYTE_GRAY)
final val OffScreenImg = new BufferedImage(VisibleWidth, VisibleHeight, BufferedImage.TYPE_INT_ARGB)
final val OffScreenG = {
val res = OffScreenImg.createGraphics()
res.setColor(Color.black)
res.fillRect(0, 0, VisibleWidth, VisibleHeight)
res
}
@elidable(CONFIG) def log(what: => String): Unit =
if (showLog) Console.out.println(s"${logHeader.format(new Date())}$what")
def warn(s: String): Unit =
Console.err.println(s"Warning: $s")
}
开发者ID:Sciss,项目名称:ImperfectHough,代码行数:35,代码来源:package.scala
示例9: render
//设置package包名称以及导入依赖的类
package eu.kraml.render
import java.awt.Color
import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage
import eu.kraml.Main.EventMonitor
import eu.kraml.model.{Circle, HeatMap, PointStyle, Record}
import eu.kraml.render.heatmap._
private[render] trait RecordRenderer {
def render(overlay: BufferedImage, coordinateConverter: CoordinateConverter, records: List[Record])
(implicit progress: EventMonitor): Unit
}
private[render] class CircleRenderer(private val diameter: Int, private val color: Color) extends RecordRenderer {
private val radius = diameter/2.0
override def render(overlay: BufferedImage, coordinateConverter: CoordinateConverter, records: List[Record])
(implicit progress: EventMonitor): Unit = {
val awtG = overlay.createGraphics()
awtG.setColor(color)
val process = progress.startProcess("rendering point")
process.setMaxProgressValue(records.size)
records.foreach( r => {
val center = coordinateConverter.toCanvasCoords(r.coordinate)
val shape = new Ellipse2D.Double(center.x-radius, center.y-radius, diameter, diameter)
awtG.fill(shape)
process << 1
})
awtG.dispose()
process.indicateCompletion()
}
}
private[render] object RecordRenderer {
def getRenderer(style: PointStyle): RecordRenderer =
style match {
case Circle(d, c) => new CircleRenderer(d, c.toAWT)
case HeatMap() => new TiledRenderer(DefaultStyle)
case _ => throw new IllegalArgumentException(s"unknown point style $style")
}
}
开发者ID:jkraml,项目名称:gpsplot,代码行数:49,代码来源:RecordRenderer.scala
示例10: DefaultStyle
//设置package包名称以及导入依赖的类
package eu.kraml.render.heatmap
import java.awt.Color
import eu.kraml.model.Record
import eu.kraml.render.heatmap.TiledRenderer.{LimitedReach, PixelStyle}
import scala.math._
object DefaultStyle extends PixelStyle with LimitedReach {
private val exponent = 2
override def evaluatePixel(x: Int, y: Int, records: Traversable[((Int, Int), Traversable[Record])]): Color = {
val weight = records
.map( {
case ((c_x,c_y), points) => (math.sqrt(math.pow(c_x - x, 2) + math.pow(c_y - y, 2)), points.size)
})
.filter( {
case (distance, count) => distance < distanceCutoff
})
.map {
case (distance, count) =>
val linearFactor = (distanceCutoff - distance) / distanceCutoff
val modifiedFactor = math.pow(linearFactor, exponent)
count * modifiedFactor
}
.sum
val clipped = min(weight, 255).toInt
new Color(255, 0, 0, clipped)
}
override def distanceCutoff: Int = 70
}
开发者ID:jkraml,项目名称:gpsplot,代码行数:35,代码来源:DefaultStyle.scala
示例11: Body
//设置package包名称以及导入依赖的类
package core.models
import java.awt.Color
import core.universe.UniverseConstants._
import Vector2D._
case class Body(position: Vector2D = Zero,
velocity: Vector2D = Zero,
force: Vector2D = Zero,
mass: Double = 0.1,
color: Color = Color.BLACK) {
require(mass > 0, "Mass cannot be negative or zero")
def +(that: Body): Body = {
val totalMass = mass + that.mass
val x = (position.x * mass + that.position.x * that.mass) / totalMass
val y = (position.y * mass + that.position.y * that.mass) / totalMass
copy(Vector2D(x, y), Zero, Zero, totalMass)
}
def forceBetween(that: Body): Vector2D = {
val distance = this.position.distance(that.position)
val squaredDistance = Math.pow(distance, 2)
val forceMagnitude = (GRAVITATION * that.mass * mass) / squaredDistance
val unitDirection = (that.position - position) / distance
unitDirection * forceMagnitude
}
def applyForce(_force: Vector2D): Body = copy(force = force + _force)
def addForceFrom(that: Body): Body = copy(force = force + forceBetween(that))
def distance(that: Body): Double = this.position.distance(that.position)
def resetForce: Body = copy(force = Zero)
def updateStateVariables(): Body = {
val acceleration = force / mass
val deltaVelocity = acceleration * DISCRETIZED_TIME_STEP
val deltaPosition = (velocity + (deltaVelocity / 2.0)) * DISCRETIZED_TIME_STEP
copy(position = this.position + deltaPosition, velocity = this.velocity + deltaVelocity)
}
}
开发者ID:sumanyu,项目名称:n-body-akka,代码行数:48,代码来源:Body.scala
示例12: Cor
//设置package包名称以及导入依赖的类
package jerimum
import java.awt.Color
import br.edu.ifrn.potigol.Potigolutil._
case class Cor(vermelho: Inteiro, verde: Inteiro, azul: Inteiro) {
def color = new Color(vermelho, verde, azul)
def this(color: Color) = this(color.getRed, color.getGreen, color.getBlue)
}
object Cor {
val AMARELO = new Cor(Color.yellow)
val AZUL = new Cor(Color.blue)
val BRANCO = new Cor(Color.white)
val CIANO = new Cor(Color.cyan)
val CINZA = new Cor(Color.gray)
val CINZA_CLARO = new Cor(Color.lightGray)
val CINZA_ESCURO = new Cor(Color.darkGray)
val LARANJA = new Cor(Color.orange)
val MAGENTA = new Cor(Color.magenta)
val PRETO = new Cor(Color.black)
val ROSA = new Cor(Color.pink)
val VERDE = new Cor(Color.green)
val VERMELHO = new Cor(Color.red)
}
开发者ID:potigol,项目名称:Jerimum,代码行数:26,代码来源:Cor.scala
示例13: IconService
//设置package包名称以及导入依赖的类
package ylabs.play.common.services
import java.awt.Color
import java.awt.image.{ WritableRaster, BufferedImage }
import scala.util.Random
class IconService {
def createImageWithBackground(image: BufferedImage, palette: List[Color]): BufferedImage = {
val index = new Random().nextInt(palette.length)
val backColor = palette.slice(index, index + 1).head
val raster = image.copyData(null)
val copy = new BufferedImage(image.getColorModel, raster, image.isAlphaPremultiplied, null)
for {
i ? 0 until copy.getWidth
j ? 0 until copy.getHeight
} yield {
new Color(copy.getRGB(i, j), true) match {
case c if c.getAlpha == 0 ?
copy.setRGB(i, j, backColor.getRGB)
case _ ?
}
}
copy
}
}
开发者ID:springnz,项目名称:play-app-base,代码行数:27,代码来源:IconService.scala
示例14: IconServiceTest
//设置package包名称以及导入依赖的类
package ylabs.play.common.services
import java.awt.Color
import java.awt.image.BufferedImage
import ylabs.play.common.test.{ MyPlaySpec, OneAppPerTestWithOverrides }
class IconServiceTest extends MyPlaySpec with OneAppPerTestWithOverrides {
"test background" in {
val height = 30
val width = 30
val image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
for {
i ? 0 until height
j ? 0 until width
} yield {
val color = new Color(0, 0, 0, i % 2)
image.setRGB(i, j, color.getRGB)
}
val service = new IconService
val newImage = service.createImageWithBackground(image, List(Color.red, Color.blue, Color.green))
for {
i ? 0 until height
j ? 0 until width
} yield {
val origColor = new Color(0, 0, 0, i % 2)
image.getRGB(i, j) shouldBe origColor.getRGB
if (i % 2 == 0) newImage.getRGB(i, j) should (equal(Color.red.getRGB) or equal(Color.blue.getRGB) or equal(Color.green.getRGB))
else newImage.getRGB(i, j) shouldBe origColor.getRGB
}
}
}
开发者ID:springnz,项目名称:play-app-base,代码行数:37,代码来源:IconServiceTest.scala
示例15: View
//设置package包名称以及导入依赖的类
package com.ganchurin.view
import java.awt.Color
import com.ganchurin.model.PopulationState
import com.ganchurin.reactive.Consumer
import com.typesafe.config.Config
class View(config: Config) extends Consumer[PopulationState] {
private val title = config getString "title"
private val width = config getInt "width"
private val height = config getInt "height"
private val cellSize = config getInt "cellSize"
private val gridSize = config getInt "gridSize"
private val panel = new PointPanel(width, height, cellSize, gridSize)
private val converter = new PopulationConverter(cellSize, gridSize)
new MainFrame(title, width, height, panel)
panel setBackground Color.LIGHT_GRAY
panel.initRectangles()
override def consume(value: PopulationState): Unit = {
val task = converter.toRepaintTask(value)
panel paintRectangles task.rectanglesToPaint
panel clearRectangles task.rectanglesToClear
}
}
开发者ID:ganchurin,项目名称:scalife,代码行数:30,代码来源:View.scala
示例16: PointPanel
//设置package包名称以及导入依赖的类
package com.ganchurin.view
import java.awt.geom.Rectangle2D
import java.awt.{Color, Graphics2D}
import javax.swing.JPanel
class PointPanel(width: Int, height: Int, cellSize: Int, gridSize: Int) extends JPanel {
def initRectangles(): Unit = {
val rectangles = for {
i <- 0 until width by (cellSize + gridSize)
j <- 0 until height by (cellSize + gridSize)
} yield new Rectangle2D.Double(i, j, cellSize, cellSize)
clearRectangles(rectangles)
}
def paintRectangles(rectangles: Seq[Rectangle2D.Double]): Unit = {
fillRectangles(rectangles, Color.BLACK)
}
def clearRectangles(rectangles: Seq[Rectangle2D.Double]): Unit = {
fillRectangles(rectangles, Color.WHITE)
}
private def fillRectangles(rectangles: Seq[Rectangle2D.Double], color: Color) {
val g = getGraphics
val g2d = g.asInstanceOf[Graphics2D]
g2d setColor color
rectangles foreach g2d.fill
}
}
开发者ID:ganchurin,项目名称:scalife,代码行数:32,代码来源:PointPanel.scala
示例17: RGB
//设置package包名称以及导入依赖的类
package example
import java.awt.Color
import io.flatmap.ml.som.GaussianSelfOrganizingMap
import io.flatmap.ml.util.Plot
import org.apache.spark.mllib.linalg.DenseVector
import org.apache.spark.sql.SparkSession
object RGB {
def main(args: Array[String]): Unit = {
implicit val sparkSession =
SparkSession
.builder
.appName("rgb-clustering")
.getOrCreate()
val rgb = sparkSession.sparkContext
.textFile("data/rgb.csv")
.map(_.split(",").map(_.toDouble / 255.0))
.map(new DenseVector(_))
val (som, params) =
GaussianSelfOrganizingMap(24, 24, sigma = 0.5, learningRate = 0.3)
.initialize(rgb)
.train(rgb, 20)
Plot.errors(params.errors.reverse)
Plot.som(f"Trained SOM (error=${params.errors.head}%1.4f)", som.codeBook, "trained_som.png") {
case red :: green :: blue :: Nil =>
new Color((red*255.0).toInt, (green*255.0).toInt, (blue*255.0).toInt).getRGB.toDouble
case _ => Color.white.getRGB.toDouble
}
}
}
开发者ID:ShokuninSan,项目名称:som,代码行数:35,代码来源:RGB.scala
示例18: GaussianSelfOrganizingMapSpec
//设置package包名称以及导入依赖的类
package io.flatmap.ml.som
import java.awt.Color
import breeze.linalg.DenseMatrix
import breeze.numerics.closeTo
import io.flatmap.ml.util.Plot
import org.apache.spark.mllib.linalg.DenseVector
import org.apache.spark.mllib.random.RandomRDDs
import org.scalatest._
import util.TestSparkContext
class GaussianSelfOrganizingMapSpec extends FlatSpec with Matchers with BeforeAndAfterEach with TestSparkContext {
"train" should "return a fitted SOM instance" in {
val path = getClass.getResource("/rgb.csv").getPath
val rgb = sparkSession.sparkContext
.textFile(path)
.map(_.split(",").map(_.toDouble / 255.0))
.map(new DenseVector(_))
val som = GaussianSelfOrganizingMap(6, 6, _sigma = 0.5, _learningRate = 0.3).initialize(rgb)
val initialCodeBook = som.codeBook.copy
val codeBookVectorToRGB: List[Double] => Double = {
case red :: green :: blue :: Nil =>
new Color((red*255.0).toInt, (green*255.0).toInt, (blue*255.0).toInt).getRGB.toDouble
case _ => Color.white.getRGB.toDouble
}
Plot.som("Initial SOM", som.codeBook, "initial_som.png")(codeBookVectorToRGB)
val (newSom, params) = som.train(rgb, 20)
Plot.som(f"Trained SOM (error=${params.errors.head}%1.4f)", newSom.codeBook, "trained_som.png")(codeBookVectorToRGB)
Plot.errors(params.errors.reverse)
newSom.codeBook should not equal initialCodeBook
assert(closeTo(params.errors.head, 0.15, relDiff = 1e-2))
}
}
开发者ID:ShokuninSan,项目名称:som,代码行数:37,代码来源:GaussianSelfOrganizingMapSpec.scala
示例19: Test
//设置package包名称以及导入依赖的类
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
object Test {
def main(args: Array[String]) {
val image=new BufferedImage(400,400,BufferedImage.TYPE_4BYTE_ABGR)
val graphics=image.createGraphics()
graphics.setColor(Color.red)
graphics.drawArc(-50,-50,100,100,0,360)
graphics.setColor(Color.blue)
graphics.fillArc(-50,-50,100,100,0,360)
ImageIO.write(image,"jpg",new File("/home/yuan/workspace/IdeaProjects/ParallelizeHeatmap/source/p.jpg"))
}
}
开发者ID:yuanzhaokang,项目名称:ParallelizeHeatmap,代码行数:18,代码来源:Test.scala
示例20: Pi
//设置package包名称以及导入依赖的类
package com.loopfor.pi
import java.awt.{AlphaComposite, Color, Font, RenderingHints}
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import scala.io.Source
object Pi {
private val Rows = 500
private val Cols = 2000
private val Watermark = "?"
def main(args: Array[String]): Unit = {
val lines = Source.fromFile("pi-formatted.txt").getLines
// Calculate width and height of single row of digits.
val font = new Font("Source Code Pro", Font.PLAIN, 10)
var gr = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB).createGraphics()
val (width, height) = try {
gr.setFont(font)
val metrics = gr.getFontMetrics
(metrics.stringWidth("0" * Cols), metrics.getHeight * Rows)
} finally
gr.dispose()
val image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
// Render all digits.
gr = image.createGraphics()
gr.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY)
gr.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
gr.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY)
gr.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE)
gr.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON)
gr.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
gr.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
gr.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE)
gr.setFont(font)
gr.setColor(Color.BLACK)
lines.foldLeft(0) { (r, line) =>
gr.drawString(line, 0, (r + 1) * gr.getFontMetrics.getAscent)
r + 1
}
// Render the Pi symbol overlay.
gr.setFont(new Font("Symbol", Font.PLAIN, 6000))
gr.setColor(Color.BLUE)
gr.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.8F))
val bounds = gr.getFontMetrics.getStringBounds(Watermark, gr)
val x = (width - bounds.getWidth) / 2
val y = -bounds.getY - (height - bounds.getHeight) / 2
gr.drawString(Watermark, x.toInt, y.toInt)
gr.dispose()
ImageIO.write(image, "PNG", new File("pi-poster.png"))
}
}
开发者ID:davidledwards,项目名称:huge-pi,代码行数:59,代码来源:Pi.scala
注:本文中的java.awt.Color类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论